Simple java binary search


  • -1
    J
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int[] result = {0,0};
            int index1 = 0;
            int index2 = 0;
            for(int i = 0; i < numbers.length - 1; i++ ){
                index1 = i + 1;
                if(numbers[i] > target) return result;
                int dif = target - numbers[i];
                int low = i+1, high = numbers.length - 1;
                while(!(low > high)){
                    int mid = low + (high - low) / 2;
                    if(numbers[mid] == dif) {
                        index2 = mid + 1;
                        result[0] = index1;
                        result[1] = index2;
                        return result;
                    }
                    if(numbers[mid] > dif) high = mid -1;
                    if(numbers[mid] < dif) low = mid + 1;
                }
            }
           return result;
        }
    }

Log in to reply
 

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