leetcode刷题记录-Two Sum

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的方式保存。

解题源码:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         map<int, int> finder;
 5         int index1 = -1;
 6         int index2 = -1;
 7         for(int i=0; i<nums.size(); ++i){
 8             int _num = target - nums[i];
 9             finder.insert(map<int, int>::value_type(_num, i));
10         }
11         for(int i=0; i<nums.size(); ++i){
12             map<int, int>::iterator itr;
13             itr = finder.find(nums[i]);
14             if (itr!=finder.end()){
15                 int j = finder[nums[i]];
16                 if (i!=j){
17                     index1 = min(i, j);
18                     index2 = max(i, j);
19                     break;
20                 }
21             }
22         }
23         vector<int> rst;
24         rst.push_back(index1+1);
25         rst.push_back(index2+1);
26         return rst;
27     }
28 };

 

posted @ 2015-11-23 22:36  leemo_0  阅读(63)  评论(0编辑  收藏  举报