leetcode :Binary Search:Two Sum II - Input array is sorted(069)

原创 2016年08月28日 16:13:12

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

http://www.cnblogs.com/grandyang/p/5185815.html


// O(n)
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int l = 0, r = numbers.size() - 1;
        while (l < r) {
            int sum = numbers[l] + numbers[r];
            if (sum == target) return {l + 1, r + 1};
            else if (sum < target) ++l;
            else --r;
        }
        return {};
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode_Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that the...
  • alw_123
  • alw_123
  • 2017年07月10日 12:11
  • 71

LeetCode167.Two Sum II - Input array is sorted题解

1. 题目描述Given an array of integers that is already sorted in ascending order, find two numbers suc...
  • lby0910
  • lby0910
  • 2017年03月08日 13:07
  • 171

leetcode——Two Sum II - Input array is sorted

原题目: Given an array of integers that is already sorted in ascending order, find two numbers such t...

leetcode题解-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 ...

[Leetcode] 167. Two Sum II - Input array is sorted 解题报告

题目: Given an array of integers that is already sorted in ascending order, find two numbers such...

LeetCode笔记:167. Two Sum II - Input array is sorted

在有序数组中找出相加得到目标数字的两个数的索引

LeetCode 167. Two Sum II - Input array is sorted (双索引技术对撞指针)

一.题目: Given an array of integers that is already sorted in ascending order, find two numbers such t...

[LeetCode]Two Sum II - Input array is sorted

Question Given an array of integers that is already sorted in ascending order, find two numbers suc...
  • byamao1
  • byamao1
  • 2016年12月12日 16:49
  • 75

【LeetCode】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 the...

[leetcode] 167. Two Sum II - Input array is sorted

[leetcode] 167. Two Sum II - Input array is sorted
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode :Binary Search:Two Sum II - Input array is sorted(069)
举报原因:
原因补充:

(最多只允许输入30个字)