码迷,mamicode.com
首页 > 其他好文 > 详细

Two Sum

时间:2014-10-10 16:26:13      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   strong   sp   


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


1
#include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <iterator> 5 #include <unordered_map> 6 7 using namespace std; 8 9 class Solution { 10 public: 11 vector<int> twoSumf(vector<int> &numbers, int target) { 12 vector<int> res; 13 res.reserve(2); 14 15 for(size_t i = 0; i < numbers.size(); ++i){ 16 int sum = 0; 17 for(size_t j = i+1; j < numbers.size(); ++j){ 18 if((sum = numbers[i] + numbers[j]) == target){ 19 res.push_back(i+1); 20 res.push_back(j+1); 21 return res; 22 } 23 } 24 } 25 return res; 26 } 27 vector<int> tt(vector<int>& numbers, int target){ 28 vector<int> res; 29 res.reserve(2); 30 31 sort(numbers.begin(), numbers.end()); 32 33 for(size_t i = 0; i < numbers.size() - 1; ++i){ 34 if(target == numbers[i] + numbers[i+1]){ 35 res.push_back(i+1); 36 res.push_back(i+2); 37 return res; 38 }else if(target < numbers[i] + numbers[i+1]){ 39 break; 40 } 41 } 42 return res; 43 } 44 vector<int> twoSum(vector<int> &numbers, int target){ 45 vector<int> res; 46 res.reserve(2); 47 48 unordered_map<int, int> map; 49 for(size_t i = 0; i < numbers.size(); ++i){ 50 map[numbers[i]] = i; 51 } 52 for(size_t i = 0; i < numbers.size(); ++i){ 53 int gap = target - numbers[i]; 54 if(map.find(gap) != map.end() && map[gap] > i){ 55 res.push_back(i+1); 56 res.push_back(map[gap]+1); 57 break; 58 } 59 } 60 return res; 61 } 62 }; 63 64 int main() 65 { 66 Solution s; 67 vector<int> test = {2, 7, 11, 15}; 68 69 vector<int> res = s.twoSum(test, 19); 70 71 copy(res.begin(), res.end(), ostream_iterator<int>(cout, " ")); 72 73 return 0; 74 }

 

Two Sum

标签:style   blog   color   io   os   ar   for   strong   sp   

原文地址:http://www.cnblogs.com/OhFreedom/p/4015684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!