Simple Java solution using binary search


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

Log in to reply
 

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