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

【LeetCode】167. Two Sum II - Input array is sorted

时间:2017-07-28 17:11:17      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:blog   pre   解决   tab   asc   ems   not   https   size   

原题链接:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/tabs/description/

题目要求: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.

想法:

看到排好序的数组,首先就想到了用二分法。对于这道题目,就用目标值和首尾相加去比较,若目标值大,则首指针加1;否则尾指针减1。

代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int low = 0,high = numbers.size() - 1;
        while (numbers[low] + numbers[high] != target) {
            if (numbers[low] + numbers[high] < target)
                low++;
            else high--;
        }
        vector<int> res{low + 1,high + 1};//由于返回的是原数组的第几个,而不是下标,所以加1
        return res;
    }
};

大部分的排序数组问题都可以用二分法去解决。

【LeetCode】167. Two Sum II - Input array is sorted

标签:blog   pre   解决   tab   asc   ems   not   https   size   

原文地址:http://www.cnblogs.com/jialei-bupt/p/7251243.html

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