[LeetCode]Two Sum

来源:互联网 发布:文档管理系统源码 编辑:程序博客网 时间:2024/05/17 18:27

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

解题思路:

(1)O(nlogn)。排序,然后两个指针一前一后。因为题中说明了只有一对答案,因此不需要考虑重复的情况。

(2)O(n)。哈希表。将每个数字放在map中,历遍数组,如果出现和数组中的某一个值相加为target的时候,break。这个方法同样适用于多组解的情况。

class Solution01_0{public:vector<int> twoSum(vector<int>& nums, int target) {int i, j, sum;vector<int> result;for (i = 0; i < nums.size() - 1; i++){for (j = i+1; j < nums.size(); j++){sum = nums[i] + nums[j];if (sum == target){result.push_back(i + 1);result.push_back(j + 1);}}}/*vector<int>::iterator iter;for (iter = result.begin(); iter != result.end(); iter++){cout << *iter << endl;}*/return result;}};//  Time Limit Exceeded

此代码提交后,提示Time Limit Exceeded,看来时间复杂度不能容忍。


解题思路:  那么我们能不能用O(n)的时间复杂度去解这道题呢?很显然是可以的, 不过, 天下没有掉馅饼的事情啦, 既然优化了时间复杂度, 我们就要牺牲空间复杂度啦。 在这里用什么呢?stack?queue?vector?还是hash_map?对于stack和queue, 除了pop外, 查找的时间复杂度也是O(n)。 明显不是我们所需要的, 那么什么数据结构的查找时间复杂度小呢?很显然是 hash_map, 查找的时间复杂度理想情况下是O(1)。 所以我们先来考虑hash_map, 看看hash_map怎么求解这个问题。我们可以先把这个数组的所有元素存到hashmap中, 一次循环就行, 时间复杂度为O(n),之后对所给数组在进行遍历, 针对其中的元素我们只要用another_number = target-numbers[i],之后用hashmap的find function来查找这个值,如果存在的话,在进行后续比较(详见代码),如果不存在的话,继续查找。

class Solution01{public:vector<int>twoSum(vector<int> &nums, int target){int i, sum;vector<int> result;map<int, int> hmap;if (nums.size() <= 1)return result;for (i = 0; i < nums.size(); ++i){hmap[nums[i]] = i;}for (int i = 0; i < nums.size(); ++i){int reat_val = target - nums[i];if (hmap.find(reat_val) != hmap.end()){int index = hmap[reat_val];if (index == i)continue;if (index < i){result.push_back(index + 1);result.push_back(i + 1); return result;}else{result.push_back(i + 1);result.push_back(index + 1);return result;}}}}};

0 0