您的位置:首页 > 其它

1.TwoSum

2017-05-13 15:21 92 查看
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].

(给定一个整型数组,返回其中和为指定数值的两个数的下标。

假定输入数组有唯一解,且不能使用同一个数两次。)

找到一个数组中和为指定数值的两个数并不难,遍历数组中的元素即可,实现起来并不难。

解法一:

vector<int> TwoSum::TwoSum1(vector<int>& nums, int target)
{
vector<int> result;
for (int i = 0; i < nums.size(); i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
if (nums[i] + nums[j] == target)
{
result.push_back(i);
result.push_back(j);
return result;
}
else if (nums[i] + nums[j] > target)
{
break;
}
}
}
return result;
}


上述解法的时间复杂度为O(n^2)。

OJ是不会让它过的。

解法二:

#include <unordered_map>

vector<int> TwoSum::TwoSum2(vector<int>& nums, int target)
{
vector<int> result;
// 创建一个哈希表
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); i++)
{
// 遍历时直接查找对应值是否存在哈希表中
int targetNum = target - nums[i];
if (hash.find(targetNum) != hash.end())
{
result.push_back(hash[targetNum]);
result.push_back(i);
return result;
}
// 哈希表的键值对为:数组中元素的值,该元素的下标值
// 这样在查找到两个数的时候便于返回下标
hash[nums[i]] = i;
}

return result;
}


上述代码即可Accept。

测试代码:

TwoSum twoSum;
vector<int> input{ 2, 7, 11, 15 };
vector<int> result = twoSum.TwoSum1(input, 9);
//vector<int> result = twoSum.TwoSum2(input, 9);
for (vector<int>::iterator it = result.begin(); it != result.end(); ++it)
{
cout << *it << "\n";
}
cout << endl;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode TwoSum