[Leetcode]1Two Sum

来源:互联网 发布:python和javascript 编辑:程序博客网 时间:2024/04/25 13:11

Given an array of inergers, 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

方法一:

使用STL中定义的unorder_map将vector中元素的value 和 indice存入。遍历数组,找到两个相加是target的值。

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        unordered_map<int, int> mapping;vector<int> results;for(int i = 0; i < numbers.size(); ++i){mapping[numbers[i]] = i;}for(int i = 0; i < numbers.size(); ++i){const int gap = target - numbers[i];if(mapping.find(gap) != mapping.end() && mapping[gap] > i){results.push_back(i+1);results.push_back(mapping[gap]+1);break;}}return results;    }};
</pre><pre code_snippet_id="621500" snippet_file_name="blog_20150317_4_3955113" name="code" class="cpp"><pre name="code" class="cpp">class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        int i, sum;          vector<int> results;          map<int, int> hmap;          for(i=0; i<numbers.size(); i++){              if(!hmap.count(numbers[i])){                  hmap.insert(pair<int, int>(numbers[i], i));              }              if(hmap.count(target-numbers[i])){                  int n=hmap[target-numbers[i]];                  if(n<i){                      results.push_back(n+1);                      results.push_back(i+1);                      //cout<<n+1<<", "<<i+1<<endl;                      return results;                  }                }          }          return results;      }};


0 0