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

2023-05-28,,

问题描述:

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

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
int n = nums.capacity();
for(int i=;i<n;++i)
{
int i1 = nums.at(i);
for(int j=i+;j<n;++j)
{
if(i1+nums.at(j)==target)
{
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
};

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

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
unordered_map<int,int> hash;
int n = nums.size();
for(int i=;i<n;i++)
{
if(hash.find(target-nums[i])!=hash.end())
{
result.push_back(hash[target-nums[i]]);
result.push_back(i);
return result;
}
hash[nums[i]] = i;
}
return result;
}
};

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

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
int n = nums.size();
int max=, min=;
for (int i = ; i < n; i++)
{
if (nums[i] > max)
max = nums[i];
if (nums[i] < min)
min = nums[i];
} int* repeat_tag = new int[max - min + ]();
int diff;
for (int i = ; i < n; i++)
{
diff = target - nums[i];
if (diff <= max && diff >= min)
{
repeat_tag[diff - min]= i;
}
}
for (int i = ; i < n; i++)
{
if (repeat_tag[nums[i] - min] != )
{
if (i != repeat_tag[nums[i] - min])
{
result.push_back(i);
result.push_back(repeat_tag[nums[i] - min]);
return result;
}
}
}
return result;
}
};

1.Two Sum(c++)(附6ms O(n) accepted 思路和代码)的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。