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

[LeetCode] Two Sum系列

时间:2015-09-22 14:34:47      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of integers that is already sorted in ascending order, 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

分析:

有序的这道题比较自然的能想到单趟快排的思想,复杂度为O(n)。在数组的两端分别设一个指针,如果两数之和大于target,则左移尾指针;小于target则右移头指针,直到遇到一对和等于target的整数。

代码:

class Solution{
public:
    vector<int> TwoSum(vector<int> nums, int target){
        vector<int> ret(2,-1);
        int begin=0;
        int end = nums.size()-1;
        while(begin<end){
             int tempSum = nums[begin]+nums[end];
             if(tempSum > target)
                  end--;
             else if(tempSum < target)
                  begin++;
             else
                  break;  
        }
        ret[0]=begin+1;
        ret[1]=end+1;
        return ret;
    }  
}    
技术分享
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ret={-1,-1};
        int begin=0;
        int end=nums.length-1;    
        while(begin<end){
            int tempSum = nums[begin]+nums[end];
            if(tempSum>target)
                end--;
            else if(tempSum<target)
                begin++;
            else
                break;
        }
        ret[0]=begin+1;
        ret[1]=end+1;
        return ret;  
    }
}
View Code

 

延伸思考:

试想想这道题的变种, 如果去掉这个假设(有且仅有一对数满足要求),也就是说可能一对符合要求的都没有,也有可能有多对,要求全部输出。

 

[LeetCode] Two Sum系列

标签:

原文地址:http://www.cnblogs.com/eaglet-weixi/p/4828653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
分享档案
周排行
mamicode.com排行更多图片
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!