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

Note:

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

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

中文理解:给定一个排序好的数组,找出数组中的两个元素,使得两个数的和为target,返回两个元素的下标。

解题思路:由于数组是排序好的,所以可能采用两个下标,分别是i=0,j=numbers.length-1,在i<j条件下,若两个元素之和小于target,i++,若两个元素之和大于target,j--,若两个元素之和等于target,返回i+1,j+1。

代码(java):

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int []res=new int[2];
        int i=0,j=numbers.length-1;
        while(i<j){
            if(numbers[i]+numbers[j]<target){
                i++;
            }
            else if(numbers[i]+numbers[j]>target){
                j--;
            }
            else if(numbers[i]+numbers[j]==target){
                res[0]=i+1;
                res[1]=j+1;
                break;
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/87876797