Click here to try this problem on Leetcode
Problems with tag: Array
Problems with tag : Hash Table
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
思路:这道题目比较简单,直接建立Hash Table来解决就可以了。方法是,先建立一个nums数组的Hash Table;然后for-loop依次遍历每个元素,看是否能够在Hash Table中找到target - nums[i]
,如果能够找到,就返回i
和target - nums[i]
在Hash Table中对应的下标。
C++代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int,int> map;
for(int i = 0; i < nums.size(); i++){
int gap = target - nums[i];
if(map.find(gap) != map.end())
res = {i, map[gap]};
else
map[nums[i]] = i;
}
return res;
}
};
Time: O(n).
Space: O(n).
相关题目: