C++:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashMap;
for (int i = ; i < nums.size(); i++) {
if(hashMap.find(nums[i]) == hashMap.end()){
hashMap[target-nums[i]] = i;
}else{
return vector<int> {hashMap[nums[i]]+, i+};
}
}
return vector<int> {};
}
1. hashMap[value] = i 使得value + nums[i] = target
2. unordered_map其内部存储为hash、遍历无序、使用需重载operator ==以及hash_value(), map存储为树、需重载operator <; 详见文章http://blog.****.net/orzlzro/article/details/7099231
3. hashMap[nums[i]]一定比i小,因前者值为几个迭代之前的i而这里i从小到大
Python:
def twoSum(self, nums, target):
m_map = {}
for i in range(len(nums)):
if nums[i] not in m_map:
m_map[target - nums[i]] = i
else:
return[m_map[nums[i]]+1, i+1]
讨论里有更简洁代码,
for j, item in enumerate(nums, 1): #start from 1 & items are entries
i = m_map.get(item, -1) #the same as m_map[] but instead of crush, gives back -1 when couldn't find item
if i > 0:
return [i, j]
m_map[target - item] = j