首页 > 其他 > 详细

LeetCode Two Sum

时间:2014-04-27 04:55:05      阅读:533      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         unordered_map<int, int> mapping;//hash talbe
 5         vector<int> result;
 6         for(int i = 0; i < numbers.size(); i ++)
 7         {
 8             mapping[numbers[i]] = i;//hash,store every number‘s index-1
 9         }
10         for(int i = 0; i < numbers.size(); i ++)
11         {
12             const int gap = target - numbers[i];
13             if(mapping.find(gap) != mapping.end())
14             {
15                 if(i == mapping[gap]) continue; //attention:index1 < index2, cant‘t equal.
16                 result.push_back(i + 1);
17                 result.push_back(mapping[gap] + 1);
18                 break;
19             }
20         }
21         return result;
22     }
23 };
View Code

 

代码参考自https://github.com/soulmachine/leetcode

LeetCode Two Sum,布布扣,bubuko.com

LeetCode Two Sum

原文:http://www.cnblogs.com/heiqiaoxiang/p/3691880.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!