标签:== red 应该 std 查找 specific highlight 一个 使用数组
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].
给定一个整型数组,从这个数组中找出两个数,使它们的和等于给定的数,返回这两个数的索引。
注意:
分析:
本题可暴力破解,即遍历数组中的每一个元素,求出它(索引i)与给定数的差(记为diff),再在这个数组中从索引i+1查找是否存在数diff。代码如下:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
std::vector<int> rst;
int len = nums.size();
int val = 0;
int i = 0, j = 0;
bool found = false;
for (i = 0; i < len; i++)
{
val = target - nums[i];
for (j = i + 1; j < len; j++)
{
if (val == nums[j])
{
found = true;
break;
}
}
if (found)
{
rst.push_back(i);
rst.push_back(j);
break;
}
}
return rst;
}
虽然能够得出正确的解,但该方法的弊端是显而易见的:它的复杂度为O(n2)。提交结果:112ms。应该存在更简便的方法。
可以看出,上面解法中时间主要消耗在两个for循环中,第一个for是无法避免的,但第二个for是可以去掉的,可用HashMap来代替,代码如下:
vector<int> twoSum(vector<int>& nums, int target) {
std::vector<int> rst;
std::unordered_map<int, int> mp;
int len = nums.size();
for (int i = 0; i < len; i++)
mp[nums[i]] = i;
int diff = 0;
for (int i = 0; i < len; i++)
{
diff = target - nums[i];
auto iter = mp.find(diff);
if (iter != mp.end() && iter->second != i)
{
rst.push_back(i);
rst.push_back(iter->second);
break;
}
}
return rst;
}
提交结果:8ms!
标签:== red 应该 std 查找 specific highlight 一个 使用数组
原文地址:https://www.cnblogs.com/big-potato/p/12254866.html