leetcode 1 Two Sum

来源:互联网 发布:太阳帝国知乎 编辑:程序博客网 时间:2024/06/15 16:19

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

首先想到的就是每一个元素都和和后面的都加一遍,看看有没有和target相同的。代码如下

vector<int> twoSum(vector<int>& nums, int target){int key,i = 1,j = 1;vector<int>::iterator lt,lt2;vector<int> ret;lt = nums.begin();for (; lt != nums.end(); lt++){for (lt2 = lt+1,j=i+1; lt2 != nums.end(); lt2++){key = *lt + *lt2;if (key == target){ret.push_back(i);ret.push_back(j);return ret;}j++;}i++;}return ret;}

这种办法看来是可以的,但是在leetcode上提交的时候人家说超时了,想了一下,我可以将比target大的元素首先剔除掉,就能减少一部分了么就有了下面的代码

vector<int> twoSum(vector<int>& nums, int target){int key,i = 1,j = 1;vector<int>::iterator lt,lt2;vector<int> ret;lt = nums.begin();for (; lt != nums.end(); lt++,i++){if (*lt >= target)continue;for (lt2 = lt+1,j=i+1; lt2 != nums.end(); lt2++,j++){if (*lt2 >= target)continue;key = *lt + *lt2;if (key == target){ret.push_back(i);ret.push_back(j);return ret;}}}return ret;}

提交以后,还是超时。。看了一下人家的测试用例,我瞬间秒懂了,人家的vector大概有将近2万个元素,所以超时是很正常的。因为我的算法时间复杂度是O(n2)

深思熟虑,考虑了排序,考虑的bitset,都觉得行不通。只能求助度娘了。

将vector所存的元素和他的下标可以做为map的key,value值,将这些数放在map中。至此,map中的key值就是元素值,val就是下标值。

用target减去第一个元素值,得出结果,然后在map里找有没有这个结果。因为map里找key是时间复杂度常数级别,所以速度很快,如果找不着,就用target减去下一个数,依次类推,知道能够找找所找的对应元素,返回下标值。啥都不说了,看代码

vector<int> twoSum(vector<int>& nums, int target){vector<int> ret;map<int, int> hmap;//初始化一个mapfor (int i = 0; i < nums.size(); i++){hmap.insert(pair<int, int >(nums[i], i));//以key,val形式,将值全部放在map内,//key为数值,val为下标}for (int i = 0; i < nums.size(); i++){int j = target - nums[i];//先看第一个值与其对应的值有没有if (hmap.count(j)){int n = hmap[j];//如果有的话,就得到其下标if (i>n){ret.push_back(n + 1);//将找到的值放入返回的vector中。ret.push_back(i + 1);return ret;}}}return ret;}

这次终于提交上去了,因为只循环了一次,所以时间复杂度为O(N).

0 0
原创粉丝点击