Simple Java Solution using binary search


  • 3
    D
    public class Solution {
        public boolean search(int[] nums, int target) {
            int l=0,r=nums.length-1;
            while(l<=r){
                int mid=l+(r-l)/2;
                if(nums[mid]==target) return true;
                if(nums[l]<nums[mid]){
                    if(nums[l]<=target&&target<nums[mid]){
                        r=mid-1;
                    }else{
                        l=mid+1;
                    }
                }else if(nums[l]>nums[mid]){
                    if(nums[mid]<target&&target<=nums[r]){
                        l=mid+1;
                    }else{
                        r=mid-1;
                    }
                }
                else{
                    l++;
                }
            }
            return false;
        }
    }

Log in to reply
 

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