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].
這一題最簡單的思路就是利用冒泡排序的思想,每兩個數碰一下,然後看看是不是等於target,所以很明顯,時間複雜度是,這個思路我就不寫了很簡單,leetcode排序比較靠前的寫法都是利用了map這種數據結構,思路如下:
首先找到當前遍歷的數的餘數(相對於target)
然後和之前的數進行查找,是否能找到這個餘數,
找到即返回結果,找不到則將當前的數和index壓入map中,
這樣在查找中採用的是hash查找,相對於遍歷要快,時間複雜度是log(n)所以一共是nlog(n)的時間複雜度。
以下是我的方案:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector <int> result;
int num = nums.size();
map <int,int> front_elem;
for(int i = 0; i <num; i++)
{
int target_left = target - nums[i];
if(front_elem.find(target_left) != front_elem.end()) //核心知識點,當採用map的find的時候,如果find不到目標元素,返回的是.end(),但這個不是map最後一個迭代器,而是最後一個元素的下一個的迭代器,可以理解爲是結束迭代器
{
result.push_back(front_elem[target_left]);
result.push_back(i);
return result;
}
else
{
front_elem.insert(pair<int,int>(nums[i],i));
}
}
return result;
}
};
參考:https://stackoverflow.com/questions/9961742/time-complexity-of-find-in-stdmap