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

Two Sum

时间:2015-03-21 18:24:54      阅读:124      评论: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

解决原理:

数组以升序排序

从数组S头、尾同时遍历数组,i为头端索引,j为尾端索引

若S[i]+S[j]=target,则返回对应索引

若S[i]+S[j]>target,则j--

否则i++

代码:

 

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         int i = 0;
 5         int j = numbers.size()-1;
 6         int sum;
 7         vector<int> rs;
 8         vector<int> tmp;
 9         
10         for(int k = 0; k < numbers.size(); k++) 
11             tmp.push_back(numbers[k]);
12             
13         sort(tmp.begin(), tmp.end());
14         while(i < j){
15             sum = tmp[i] + tmp[j];
16             if(sum == target){
17                 int m = 0;
18                 while(numbers[m] != tmp[i]) m++;
19                 int n = 0;
20                 while(numbers[n] != tmp[j]) n++;
21                 if(n == m){
22                     n++;
23                     while(numbers[n] != tmp[j]) n++;
24                 }
25                 
26                 rs.push_back(m>n?n+1:m+1);
27                 rs.push_back(m>n?m+1:n+1);
28                 return rs;
29             }else if(sum < target){
30                 i++;
31             }else{
32                 j--;
33             }
34         }
35         return rs;
36     }
37 };

 

Two Sum

标签:

原文地址:http://www.cnblogs.com/ISeeIC/p/4355803.html

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