Simple binary search Java Solution


  • 0
    L
    public int[] twoSum(int[] numbers, int target) {
            if(numbers == null || numbers.length <2) {
                throw new IllegalArgumentException("Input array is empty or less than 2 numbers");
            }
    
            int len=numbers.length, low, high, mid;
            for(int i=0; i<len-1; i++) {
                low=i+1;
                high=len-1;
                mid=(low+high)/2;
    
                while (low <= high) {
                    if( numbers[mid] == target - numbers[i]) {
                        return new int[]{i+1, mid+1};
                    } else if( numbers[mid] < target - numbers[i]) {
                        low = mid+1;
                    } else {
                        high = mid-1;
                    }
                    mid=(low+high)/2;
                }
            }
            return null;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.