167. Two Sum II

来源:互联网 发布:逗猫软件 编辑:程序博客网 时间:2024/06/08 00:28

题目如下:

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

public class Solution {    public int[] twoSum(int[] numbers, int target) {        int left = 0;        int right = numbers.length-1;        int[] ans = new int[2];                if(numbers==null||numbers.length<2) return ans;                while(left<right){            int sum = numbers[left]+numbers[right];            if(sum==target){                ans[0] = left+1;                ans[1] = right+1;                break;            }else if(sum>target){                right--;            }else left++;        }        return ans;    }}
需要注意的:

1. numbers的原始判断

2. sum的定义要在while循环里面

3. ans的答案返回的是index,但是题目中的index是从1开始的,所以返回的时候要+1.

0 0