【Leetcode】Two Sum II - Input array is sorted

来源:互联网 发布:语文试卷编制软件 编辑:程序博客网 时间:2024/05/17 07:50

题目链接: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

思路:

easy。。看代码就好了 O(n)时间复杂度

有个坑要注意,tag有binary search 不代表有O(logn)的解法,不必去尝试设计一个O(logn)的解法。。因为根本木有

维基百科给的 3sum (无论有序无序,无序可以对数组预处理在O(nlogn)复杂度下变为有序)的最优解时间复杂度为O(n^{2}/({\log n}/{\log \log n})^{2/3})   如果2sum如果能被O(logn)解决,3sum就能在O(nlogn)复杂度下解决(对每一个数num 都用2sum的算法查找target-num)

但上式等于 nlogn*(n*(loglogn^(2/3))/logn^(5/3)), 很明显当lim n->无穷大,n*(loglogn^(2/3))/logn^(5/3)>1,即3sum最优解时间复杂度大于O(nlogn),所以2sum最优解不可能达到O(logn)。

算法:

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


0 0
原创粉丝点击