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

来源:互联网 发布:人人秀 制作软件 编辑:程序博客网 时间:2024/06/06 07:26

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


开始用了两个数组,嵌套着查找,时间方面超出限制,后来看别人的做法恍然大悟,采用shrink的思想。

至于第二个数组newArr,纯粹是因为题目要求index 不是zero-based。


    public int[] twoSum(int[] numbers, int target{        int [] arr=new int[2];        int [] newArr=new int[2];        int start=0;        int end=numbers.length-1;        while(numbers[start]+numbers[end]!=target){            if(numbers[start]+numbers[end]<target){                start++;            }else{                end--;            }        }        newArr[0]=start+1;        newArr[1]=end+1;        return newArr;    }


0 0
原创粉丝点击