*Java* one pass 1ms solution (binary search)


  • 0
    E

    Pleas leave your comment if any question with this solution :)

    public int search(int[] nums, int target) {
        int L=nums.length, lo=0, hi=L-1;
    
        while(lo<=hi) {
            int mid = lo + ((hi-lo)>>1);
            if(nums[mid]>target) {
                if(nums[mid]<nums[lo]) hi = mid-1;
                else if(nums[hi]==target) return hi;
                else if(nums[lo]>target) lo = mid+1;
                else hi = mid-1;
            }
            else if(nums[mid]<target) {
                if(nums[mid]>nums[lo]) lo = mid+1;
                else if(nums[hi]==target) return hi;
                else if(nums[lo]>target) lo = mid+1;
                else hi = mid-1;
            }
            else return mid;
        }
        return -1;
    }

Log in to reply
 

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