[LeetCode]Two Sum II - Input array is sorted

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};
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值