首页 > 其他 > 详细

[Leetcode] Two Sum

时间:2014-03-29 00:13:04      阅读:503      评论:0      收藏:0      [点我收藏+]

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         vector<int> v = numbers;
 5         sort(v.begin(), v.end());
 6         int a = 0, b = v.size() - 1;
 7         while (a < b) {
 8             if (v[a] + v[b] > target) {
 9                 b--;
10             } else if (v[a] + v[b] < target) {
11                 a++;
12             } else {
13                 break;
14             }
15         }
16         for (int i = 0; i < v.size(); ++i) {
17             if (v[a] == numbers[i]) {
18                 a = i + 1;
19                 break;
20             }
21         }
22         for (int i = v.size() - 1; i >= 0; --i) {
23             if (v[b] == numbers[i]) {
24                 b = i + 1;
25                 break;
26             }
27         }
28         vector<int> res;
29         res.push_back(a > b ? b : a);
30         res.push_back(a > b ? a : b);
31         return res;
32     }
33 };
bubuko.com,布布扣

[Leetcode] Two Sum,布布扣,bubuko.com

[Leetcode] Two Sum

原文:http://www.cnblogs.com/easonliu/p/3630629.html

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