admin 管理员组

文章数量: 1087817

[勇者闯LeetCode] 1. Two Sum

[勇者闯LeetCode] 1. Two Sum

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Information

  • Tags: Array | Hash Table
  • Difficulty: Easy

Solution

利用额外的map存储元素的值和位置。

Python Code

class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""dictionary = {}for n, num in enumerate(nums):completement = target - numif completement in dictionary:return [n, dictionary[completement]]dictionary[num] = n

C++ Code

class Solution {
public:vector<int> twoSum(vector<int>& nums, int target) {unordered_map<int, int> lookup;for (int i = 0; i < nums.size(); i++) {if (lookup.count(target - nums[i])) {return {lookup[target - nums[i]], i};}lookup[nums[i]] = i;}return {};}
};

本文标签: 勇者闯LeetCode 1 Two Sum