Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].C++实现: 时间复杂度为O(n).
原题目:https://leetcode.com/problems/two-sum/description/
class Solution {
public:vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
vector<int> result;
for(int i=0;i<nums.size();i++)
{
int tofind= target-nums[i];
if(hash.find(tofind)!=hash.end())
{
result.push_back(hash[tofind]);
result.push_back(i);
return result;
}
hash[nums[i]]=i;
}
}
};
其中 unordered_map 就是hashmap,是vector实现的,为什么具有O(n)的复杂度是因为 c++ 中 hash_map的实现方式问题
这里面 有一个关键的点 hash[nums[i]]=i; hash[] 的 “ 【】”是 KEY ,= 后面是对应的 value.
注意 c++ 这里vector 添加元素用的是 push_back(), 还有一个要注意的地方是 hash.find(tofind)!= hash.end(); 这里可能是有一个 遍历的过程 遍历到最后还是找不到的意思
python实现:
Class Solution(object):
def twoSum(self,nums,target):
if len(nums)<=1:
return False
buff_dict={}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]],i]
else:
buff_dict[target-nums[i]]=i
注意点:
http://www.iplaypy.com/jichu/tuple.html
python 元组,List,dict的用法