Java O(log N) Binary search solution


  • 0
    E
    class Solution {
        public int search(int[] nums, int target) {
            if (nums == null || nums.length == 0) return -1;
            
            int start = 0, end = nums.length - 1;
            while (start + 1 < end) {
                int mid = start + (end - start) / 2;
                if (nums[mid] > nums[start]) {
                    if (nums[start] <= target && target<= nums[mid])
                        end = mid;
                    else
                        start = mid;
                }
                else {
                    if (nums[mid] <= target && target <= nums[end])
                        start = mid;
                    else
                        end = mid;
                }
            }
            if (nums[start] == target)
                return start;
            else if (nums[end] == target)
                return end;
            else
                return -1;
        }
    }
    

Log in to reply
 

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