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

  这是我在Leetcode上做的处女题,题目虽然简单,但也是考察了一些复杂度的问题。一开始一直,后来参考了http://blog.csdn.net/lanxu_yy/article/details/11679415,才用map跑成功。核心想法就是 ‘a+b=t 等价于 寻找一个a使其等于t-b’

  做此题的收获:强化了对map应用的理解。这里好像用hashmap更好一些,但是我暂时还没有具体了解hash算法,稍后再看,下面的代码虽然提交成功了,但是却是有bug的,原因在于当出现相同的键时,只能存最后一个值。

  example:numbers = {1,2,4,5,4,9} ;  target = 8;此时就是错的,等以后有好的解决方案时再修正。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         
 5         vector<int> s_num;
 6         map<int,int> map_data;
 7         for (int i = 1; i < numbers.size(); ++i)
 8         {
 9             map_data.insert(make_pair(target - numbers[i],i+1));
10         }
11         for (int i = 0; i < map_data.size(); ++i)
12         {
13             map<int,int>::iterator iter = map_data.find(numbers[i]);
14             if(iter != map_data.end() && iter->second != i + 1)
15             {
16                 if((i+1) > iter->second)
17                 {
18                     s_num.push_back(iter->second);
19                     s_num.push_back(i + 1);
20                 }
21                 else
22                 {
23                     s_num.push_back(i + 1);
24                     s_num.push_back(iter->second);
25                 }
26                 return s_num;
27             }
28         }
29     }
30 };

 

posted @ 2015-03-25 20:01  小痴_r  阅读(136)  评论(0编辑  收藏  举报