Java AC


  • 0
    A
    public int search(final int[] nums, final int target) {
            int smallestElementIndex = findSmallestElementIndex(nums);
            
            int index;
            if (smallestElementIndex == 0) {
                index = Arrays.binarySearch(nums, target);
            } else if (nums[0] <= target && target <= nums[smallestElementIndex-1]) {
                index = Arrays.binarySearch(nums, 0, smallestElementIndex, target);
            } else {
                index = Arrays.binarySearch(nums, smallestElementIndex, nums.length, target);
            }
            
            return index < 0 ? -1 : index;
        }
        
        private int findSmallestElementIndex(final int[] nums) {
            int left = 0, right = nums.length - 1;
            while (left < right) {
                int mid = left + (right - left)/2;
                if (nums[mid] > nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            return left;
        }
    

Log in to reply
 

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