Java solution ---easy to understand


  • 0
    L
    public boolean search(int[] nums, int target) {
            if(nums==null || nums.length==0) return false;
            boolean res =false;
            if(nums.length==1){
                return nums[0]==target?true:false;
            }
            int left=0,right=nums.length-1;
            while(left<right-1){
                int mid=left+(right-left)/2;
                if(nums[mid]==target){
                    res=true;
                    break;
                }
                if(nums[mid]<target){
                    if(nums[mid]==nums[right]){
                        right--;
                    }else if(nums[mid]<nums[right] && target>nums[right]){
                        right=mid;
                    }else{
                        left=mid;
                    }
                }else{
                    if(nums[mid]==nums[left]){
                        left++;
                    }else if(nums[mid]>nums[left] && target<nums[left]){
                        left=mid;
                    }else{
                        right=mid;
                    }
                }
            }
            if(left==right-1){
                if(nums[left]==target || nums[right]==target){
                    res=true;
                }else {
                    res=false;
                }
            }
            return res;
        }

Log in to reply
 

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