167. Two Sum II - Input array is sorted

167. 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

给定一个已经按升序排序的整数数组,找到两个数字,使它们相加到一个特定的目标数。 函数twoSum应该返回两个数字的索引,使它们相加到目标,其中index1必须小于index2。请注意,您返回的答案(index1和index2)都不是基于零的。 您可以假设每个输入都只有一个解决方案,您可能不会使用相同的元素两次。

解题思路

利用二分搜索,在升序的数组中,从头尾开始求和,
然后与target比较选择适当的进行遍历,复杂度O(n)。

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int i = 0, j = numbers.size() - 1;
        vector<int> v;
        while(i < j) {
            int x = numbers[i] + numbers[j];  
            if(x < target) {  
                i++;  
            } else if(x > target) {  
                j--;  
            } else {
                v.push_back(i + 1);
                v.push_back(j + 1);
                return v;
            }  
        } 
    }
};
发布了69 篇原创文章 · 获赞 18 · 访问量 7万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览