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