問題描述:
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:
1 Given nums = [2, 7, 11, 15], target = 9, 2 Because nums[0] + nums[1] = 2 + 7 = 9, 3 return [0, 1].
通常很容易想到的解法是使用雙層循環遍歷給定的數組,查找是否有滿足條件的兩個數。代碼如下:
1 vector<int> addToTarget(vector<int> &num,int target)
2 {
3 vector<int> res;
4 for(auto it1 = num.begin(); it1 != num.end();++it1)
5 for(auto it2 = num.begin();it2 != num.end();++it2)
6 {
7 if(*it1 + *it2 == target && it1 != it2)
8 {
9 res.push_back(static_cast<int>(it1 - num.begin()));
10 res.push_back(static_cast<int>(it2 - num.begin()));
11 return res;
12 }
13 }
14 }
但是使用雙層循環的時間復雜度為O(n2),且兩次循環且條件不滿足時,數組的某些元素會被多次遍歷,也就是處理當前節點需要依賴於之前的部分結果,如果我們能夠保存已遍歷的元素的狀態,便可減少這種浪費的發生。所以考慮使用哈希表來存儲狀態,因為哈希表的存儲和讀取時間復雜度為O(1)。代碼如下:
1 vector<int> addToTarget(vector<int> &num,int target)
2 {
3 vector<int> res(2);
4 unordered_map<int,int> hashMap;
5 for(auto it=num.begin();it != num.end(); ++it)
6 {
7 if(hashMap.count(target - *it))
8 {
9 res[0]=hashMap[target-*it];
10 res[1]=static_cast<int>(it-num.begin());
11 return res;
12 }
13 hashMap[*it] = static_cast<int>(it-num.begin());
14 }
15 }
我們使用hashMap的鍵來保存給定數組的值,使用hashMap的值來保存給定數組的下標。使用一個循環遍歷數組,如果與當先遍歷值相加等於targe的值存在於已保存的hashMap中時,記錄當前下標和滿足值得下標並返回。時間復雜度為O(n)。