leetcode解题报告(22):Two Sum II - Input array is sorted

描述

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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

分析

用的是二分的思想。

考虑到输入的是递增的有序数组,且有且仅有一组输出结果,因此可以用两个变量,分别从数组起始处i和末尾处j开始,如果两个数相加等于target,就返回这两个下标;如果相加大于target,那么就减小j的值,如果相加小于target,那么就增加i的值,直到找到为止。

代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        /*
        Time exceeded code
        int i = 0;
        int len = 0;
        vector<int>ret;
        for(auto it = numbers.begin(); it != numbers.end(); ++it){
            int another = target - *it;
            auto index = find(it + 1,numbers.end(),another);
            if(index != numbers.end()){
                len = distance(it,index);
                break;
            }
            ++i;
        }*/
        
        int i = 0,j = numbers.size() - 1;
        while(i < j){
            if(numbers[i] + numbers[j] == target){
                vector<int>ret = {i + 1,j + 1};
                return ret;
            }else if(numbers[i] + numbers[j] > target)
                --j;
            else
                ++i;    
        }
      
    }
};
posted @ 2017-05-16 18:16  larryking  阅读(114)  评论(0编辑  收藏  举报