167. Two Sum II - Input array is

2018-02-19  本文已影响0人  Ching_Lee

找到两个值加起来和为target
使用二分查找。


class Solution {
    public int[] twoSum(int[] numbers, int target) {
       int[] num=new int[2];
        for(int i=0;i<numbers.length;i++){
            //从下一个元素之后查找target-numbers[i]
            int index=BinarySerch(numbers,i+1,target-numbers[i]);
            if(index!=-1){
               num[0]=i+1;
               num[1]=index+1; 
            }
                
        }
        
        return num;
        
    }
    
    public int BinarySerch(int[] arr,int startIndex,int e){
        int low=startIndex;
        int high=arr.length-1;
        while(low<=high){
            int mid=low+(high-low)/2;
            if(arr[mid]==e)
                return mid;
            else if(arr[mid]<e)
                low=mid+1;
            else 
                high=mid-1;
        }
        return -1;
       
    }    
    
}
上一篇 下一篇

猜你喜欢

热点阅读