LeetCode Two Sum II - Input array is sorted

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Two Sum II - Input array is sorted相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题解:

说指针从两头向中间递进. 类似Two Sum.

Time Complexity: O(n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int[] twoSum(int[] numbers, int target) {
 3         int [] res = new int[]{-1,-1};
 4         if(numbers == null || numbers.length < 2){
 5             return res;
 6         }
 7         int l = 0;
 8         int r = numbers.length-1;
 9         while(l<r){
10             if(numbers[l] + numbers[r] < target){
11                 l++;
12             }else if(numbers[l] + numbers[r] > target){
13                 r--;
14             }else{
15                 res[0] = l+1;
16                 res[1] = r+1;
17                 break;
18             }
19         }
20         return res;
21     }
22 }

 

以上是关于LeetCode Two Sum II - Input array is sorted的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode167. Two Sum II - Input array is sorted

28.leetcode167_two_sum_II

LeetCode | 0167: Two Sum II - Input array is sortedPython

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

LeetCode 167. Two Sum II - Input array is sorted

[LeetCode] Two Sum II - Input array is sorted