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]python
這種是最容易想到的思路,比較暴躁,複雜度\(O(N^2)\)。數組
題目對數a、b求和,可是返回的是等於target時a、b的下標,因而想到將數組下標與對應值做一個映射表。C++使用unordered_map
關聯容器能夠實現鍵值與真值的映射。python中使用字典來實現相似功能。app
template <class T, //鍵值類型 class T, // 映射類型 class hash = hash<key>, //哈希函數對象類型 class Pred = equal_to <key>, //相等比較函數對象類型 class Alloc = allocator < pair<cosnt key, T> > //alloctor類 >
count
size_type count (const key_type& k) const;
unordered_map
的數據以pair<const Key, T>保存,first是鍵值(key value),second是映射值(the mapped value)。賦值語句m[key value] = the mapped value
。函數
vector<int> twoSum(vector<int>& nums, int target) { vector<int> results; for(int i=0;i<nums.size();i++) { for(int j=i+1;j<nums.size();j++) { if(nums[i]+nums[j]==target) { results.push_back(i); results.push_back(j); return results; } else { continue; } } } }
vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> m; vector<int> results; //數組中的值做爲map的鍵值,其下標做爲對應的映射值 for(int i=0;i<nums.size();i++) { m[nums[i]] =i; } for(int i = 0;i<nums.size();i++) { int t = target - nums[i]; if(m.count(t) && m[t] != i) // 不能使用一樣的數兩次 { results.push_back(i); results.push_back(m[t]); break; } } return results; }
def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ #創建字典 table ={nums[i] : i for i in range(len(nums))} results = [] for i in range(len(nums)): t = target - nums[i] if table.get(t) is not None and (table.get(t) != i): results = [i, table.get(t)] break; return results