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

[解题思路]

时间复杂度O(n), 空间复杂度O(n)

首先:使用map记录已经出现的数字。map(number, index)

然后:对新的数字x,就判断 target - x是否已经出现。出现则返回结果

 1 std::vector<int> Solution::twoSum(std::vector<int> &numbers, int target)
 2 {
 3     std::map<int, int> kp;
 4     int index1, index2, index=0;
 5     for (std::vector<int>::iterator ite = numbers.begin(); ite != numbers.end(); ite ++){
 6         index ++;
 7         if (kp.find(target - *ite) != kp.end()){
 8             index2 = index;
 9             index1 = kp[target - *ite];
10             break;
11         }
12         else if(kp.find(*ite) == kp.end()){
13             kp[*ite] = index;
14         }
15     }
16     std::vector<int> ans;
17     ans.push_back(index1);
18     ans.push_back(index2);
19     return ans;
20 }

 

posted on 2014-08-13 14:07  雨歌_sky  阅读(138)  评论(0编辑  收藏  举报

导航