[LeetCode]Two Sum II - Input array is sorted

来源:互联网 发布:js math ceil 编辑:程序博客网 时间:2024/06/05 19:10

Question
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


本题难度Medium。有2种算法分别是:二叉查找法 和 双指针法(推荐)

在LeetCode上测试第一个方法用时4ms,第二个方法用时1ms

【题意】
在升序排列的数组中找到一对值,其和等于target。有且只有1种答案。

1、二叉查找法

【复杂度】
时间 O(NlogN) 空间 O(1)
有许多人认为这里的时间复杂度应该是O(logN),实际上应该为O((N/2)logN)(虽然不够精确但够准确),因为在每个元素上都要对后面进行二叉查找。

【思路】
从第1个元素开始遍历,在其后面的元素中用二叉查找法找其另一个值,找到了即返回。

【代码】

public class Solution {    public int[] twoSum(int[] numbers, int target) {        //require        int[] ans=new int[2];        //invariant        for(int i=0;i<numbers.length;i++){            int res=bs(i+1,numbers.length-1,numbers,target-numbers[i]);            if(res!=-1){                ans[0]=i+1;ans[1]=res+1;                return ans;            }        }        //ensure        return ans;    }    private int bs(int l,int r,int[] nums, int target){        //base case        if(l>r)return -1;        int mid=(l+r)/2;        if(nums[mid]==target)return mid;        if(nums[mid]<target)return bs(mid+1,r,nums,target);        else                return bs(l,mid-1,nums,target);    }}

2、双指针法(推荐)

【复杂度】
时间 O(N) 空间 O(1)

【思路】
利用双指针ij,从两端向中间夹逼。设sum = numbers[i] + numbers[j];

  • 如果sum==target,就返回
  • 如果sum>target,就移动右边的指针
  • 如果sum<target,就移动左边的指针

【代码】

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