您的位置:首页 > 其它

LeetCode 1 Two Sum

2017-02-26 16:34 281 查看

题目

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].

解法

穷举法

题目要求在一个数组(无序)中快速找到两个数,使两个数之和等于一个给定的值。题目假设数组中肯定存在至少一组满足要求的数。最直接的方法是使用两个for循环穷举所有可能。

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i, j, sum;
vector<int> idx;
for (i = 0; i < nums.size()-1; i++) {
for (j=i+1;j<nums.size();j++) {
sum = nums[i] + nums[j];
if(sum == target) {
idx.push_back(i);
idx.push_back(j);
return idx;
}
}
}
return idx;
}
};


Hash表

虽然穷举法可以解决,但时间复杂度为O(N*N),在题目的tags看到了Hash Table,考虑用Hash表解决。

思路是遍历一遍数组,判断当前值是否在Hash表里,不在的话,加入表中(key为数值,value为索引值);如果在的话,在Hash表中查找(target-当前值),如果找到就结束,返回索引值。利用了Hash表中查找元素时间为常数的优势,该方法时间复杂度O(N), 空间复杂度O(N)。

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> hmap;
vector<int> idx;
for (int i = 0; i < nums.size(); i++) {
if (!hmap.count(nums[i])) {
hmap.insert(pair<int,int>(nums[i],i));
}
if (hmap.count(target-nums[i])) {
int j = hmap[target-nums[i]];
if (j < i) {
idx.push_back(j);
idx.push_back(i);
return idx;
}
}
}
return idx;
}
};


每个元素只能使用一次,因此要注意target = 2 * nums[i]的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode