Easy to understand Java solution. Beats 95% of solutions


  • 0
    M

    public class Solution {

    public int search(int[] nums, int target) {
         int low = 0;
        int high = nums.length-1;
        int mid;
        while(low <= high){
            mid = low + (high-low)/2;
            if(nums[mid] == target)  return mid;
            if(nums[low]<=nums[mid]){
                //first half is sorted
                //check the location of target within the first half
                if(nums[low]<=target && target< nums[mid]){
                    //low = low;
                    high = mid-1;
                }else{
                    low = mid+1;
                    //high =high;
                }
            }else{
                //second half is sorted
                //check the location of target within the second half
                if(nums[mid+1]<=target && target <= nums[high]){
                    low = mid+1;
                    //high = high;
                }else{
                    //low = low;
                    high = mid-1;
                }
            }
        }
        return -1;
    }
    

    }


Log in to reply
 

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