您的位置:首页 > 其它

leetcode刷题记录-Two Sum

2015-11-23 23:05 417 查看
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.

解题思路:

利用target减去数组中每个数得到数组的差值数组,以原题中的例子为例:{2,7,11,15}对应的差值数组为{7,2,-1,,6},然后遍历原数组,若差值数组中也包含这个数且对应索引不相等,则返回原数组该值索引与差值数组中的索引。为了让时间复杂度为O(n),差值数据需用哈希map的方式保存。

解题源码:

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> finder;
int index1 = -1;
int index2 = -1;
for(int i=0; i<nums.size(); ++i){
int _num = target - nums[i];
finder.insert(map<int, int>::value_type(_num, i));
}
for(int i=0; i<nums.size(); ++i){
map<int, int>::iterator itr;
itr = finder.find(nums[i]);
if (itr!=finder.end()){
int j = finder[nums[i]];
if (i!=j){
index1 = min(i, j);
index2 = max(i, j);
break;
}
}
}
vector<int> rst;
rst.push_back(index1+1);
rst.push_back(index2+1);
return rst;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: