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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解题思路,暴力破解的话,时间复杂度为n^2,可以采用hash思想,边遍历边寻找之前存储的值,使之和为target;以下是hash的解法。
C++版
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int>m;
vector<int>ans;
for(int i = 0; i < nums.size(); ++ i){
if(m.find(target-nums[i]) != m.end()){
ans.push_back(m[target-nums[i]]);
ans.push_back(i);
break;
}
m[nums[i]] = i;
}
return ans;
}
};
Python版
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
List = []
dic = {}
for i in range(len(nums)):
if dic.has_key(target - nums[i]):
List.append(dic[target - nums[i]])
List.append(i)
break
dic[nums[i]] = i
return List