您的位置:首页 > 其它

LeetCode Two Sum

2014-03-26 16:40 190 查看
题目:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

方法1:最直观的复杂度为O(n^2),超时。

方法2:先排序,这样的话就要记下以前的索引,转换用时O(n),排序用时O(nlgn),查找用时O(n)。

struct node {
int val;
int idx;
node(){}
node(int num, int index): val(num), idx(index) {}
bool operator < (const node& other) const {
return val < other.val;
}
};

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> ans(2);
vector<node> res(numbers.size());
//O(n)
for(int i = 0; i < numbers.size(); i++)
res[i] = node(numbers[i], i+1);
//O(nlgn)
sort(res.begin(), res.end());
int begin = 0, end = numbers.size()-1;
//O(n)
while(begin < end) {
int tmp = res[begin].val + res[end].val;
if(target == tmp) {
ans[0] = min(res[begin].idx, res[end].idx);
ans[1] = max(res[begin].idx, res[end].idx);
break;
}
else if(target > tmp)
begin++;
else
end--;
}
return ans;
}
};


方法3:使用哈希表(利用stl中的unordered_map实现),边建表,边判断,复杂度为最优O(n)。

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> ans(2);
int len = numbers.size();
unordered_map<int, int> hash_table;
for(int i = 0; i < len; i++) {
//表中存在与它和为target的数
int other = target - numbers[i];
if(hash_table.find(other) != hash_table.end()) {
ans[0] = hash_table[other];
ans[1] = i+1;
break;
}
//不在hash表中,加入
if(hash_table.find(numbers[i]) == hash_table.end())
hash_table[numbers[i]] = i+1;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: