LeetCode 167. Two Sum II - Input array is sorted

189 篇文章 0 订阅
162 篇文章 0 订阅

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.

Note:

  • 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.

Example:

Input: numbers = [2,7,11,15], target = 9

Output: [1,2]

Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

 

 

方法1:

双层遍历,时间复杂度O(N*N)

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] newArray=new int[2];
        for(int i=0;i<numbers.length-1;i++){
            for(int j=i+1;j<numbers.length;j++){
                if(numbers[i]+numbers[j]==target){
                    newArray[0]=i+1;
                    newArray[1]=j+1;
                    return newArray;
                }
            }
        }
        return null;
    }
}

 

 

方法二:

方法一的暴力解法没有充分利用原数组的性质--有序

有序?如果有序的话想到二分搜索。

二分搜索法是O(lgN)的复杂度,所以总的时间复杂度是O(n lgN)的复杂度,比O(N*N)快了很多倍

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int length=numbers.length;
        if(length<2)
            return null;
        int[] newArray=new int[2];
        for(int i=0;i<length-1;i++){
            int index=binearySearch(numbers,i+1,length-1,target-numbers[i]);
            if(index!=-1){
                newArray[0]=i+1;
                newArray[1]=index+1;
                return newArray;
            }
        }
        return null;
    }
    
    //[l,r]
    private int binearySearch(int[]numbers,int l,int r,int target){
        
        while(l<=r){
            int mid=l+(r-l)/2;
            if(numbers[mid]==target)
                return mid;
            if(numbers[mid]>target){
                r=mid-1;
            }else{//numbers[mid]<target
                l=mid+1;
            }
        }
        return -1;
    }
}

 

 

方法三、

对撞指针,时间复杂度为O(n),空间复杂度为O(1)

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值