Simple Java binary search solution(kind of)


  • 0
    J
       public boolean search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
        	int mid = (left + right) / 2;
        	if (nums[mid] == target)
        		return true;
        	if (nums[mid] < nums[right]) { //right side in order.
        		if (target > nums[mid] && target <= nums[right]) {
        			left = mid + 1;
        		} else {
        			right = mid - 1;
        		}
        	} else if (nums[mid] > nums[right]){ // left side in order.
        		if (target < nums[mid] && target >= nums[left]) {
        			right = mid - 1;
        		} else {
        			left = mid + 1;
        		}
        	} else { //nums[mid] == nums[right], no idea, can only eliminate nums[right].
        		right--;
        	}
        }
        return false;
    }

Log in to reply
 

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