167

解法1,利用二分查找,对第一个i,去剩下的有序数组中查找target-numbers[i]

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] res=new int[2];
        for(int i=0;i<numbers.length;i++)
        {
            int find=binarySearch(numbers,i+1,numbers.length-1,target-numbers[i]);
            if(find!=-1)
            {
                res[0]=i+1;
                res[1]=find+1;
            }
        }
        return res;
    }
    public int binarySearch(int[] arr,int l,int r,int target)
    {
        if(l<=r)
        {
             int mid=l+(r-l)/2;
            if(arr[mid]==target)
                return mid;
             else if(arr[mid]>target)
                 return binarySearch(arr,l,mid-1,target);
            else
                return binarySearch(arr,mid+1,r,target);
        }
         else
             return -1;
        
    }
}

//解法2,碰撞指针

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

posted @ 2019-07-26 21:09  小路不会迷路  阅读(338)  评论(0编辑  收藏  举报