1.Two Sum(c++)(附6ms O(n) accepted 思路和代码)

问题描述:

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:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路1:最简单的思路就是暴力求解,即循环遍历所有的可能情形,复杂度为o(n^2). 耗时未知,leetcode: Time Limit Exceeded

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         vector<int> result;
 5         int n = nums.capacity();
 6         for(int i=0;i<n;++i)
 7         {
 8             int i1 = nums.at(i);
 9             for(int j=i+1;j<n;++j)
10             {
11                 if(i1+nums.at(j)==target)
12                 {
13                     result.push_back(i);
14                     result.push_back(j);
15                     return result;
16                 }
17             }
18         }
19         return result;
20     }
21 };

思路2:使用hash map,查询等各种操作都是常数级别的时间复杂度(最好不要使用map,map实现大都是使用红黑树,查询的时间复杂度是O(logn)),复杂度为O(n),leetcode: AC,16ms

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         vector<int> result;
 5         unordered_map<int,int> hash;
 6         int n = nums.size();
 7         for(int i=0;i<n;i++)
 8         {
 9             if(hash.find(target-nums[i])!=hash.end())
10             {
11                 result.push_back(hash[target-nums[i]]);
12                 result.push_back(i);
13                 return result;
14             }
15             hash[nums[i]] = i;
16         }
17         return result;
18     }
19 };

思路3(参考论坛中4ms的c代码):别出机杼,逆向思考,第一步找出数组中与目标值的差值(这一步可以筛选部分明显不可能得到目标值的数),第二步则是遍历数组找到哪个数是差值。复杂度:O(n). leetcode:AC,6ms,超过99.57%的结果!

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         vector<int> result;
 5         int n = nums.size();
 6         int max=0, min=0;
 7         for (int i = 0; i < n; i++)
 8         {
 9             if (nums[i] > max)
10                 max = nums[i];
11             if (nums[i] < min)
12                 min = nums[i];
13         }
14         
15         int* repeat_tag = new int[max - min + 1]();
16         int diff;
17         for (int i = 0; i < n; i++)
18         {
19             diff = target - nums[i];
20             if (diff <= max && diff >= min)
21             {
22                 repeat_tag[diff - min]= i;
23             }
24         }
25         for (int i = 0; i < n; i++)
26         {
27             if (repeat_tag[nums[i] - min] != 0)
28             {
29                 if (i != repeat_tag[nums[i] - min])
30                 {
31                     result.push_back(i);
32                     result.push_back(repeat_tag[nums[i] - min]);
33                     return result;
34                 }
35             }
36         }    
37         return result;
38     }
39 };
原文地址:https://www.cnblogs.com/nice-forever/p/6200583.html