My straight forward Java solution with explanation

  • 0
    • The idea is straightforward
    • since only one rotation is made, there are two sorted arrays
    • find the pivot, and decide to search the target in which array
    • binary search then

    Attached is the accepted code

    public class Solution {
      public int search(int[] nums, int target) {
        int n = nums.length;
        if(n==0 || (n==1 && nums[0]!=target)) return -1;
        if(n==1 && nums[0]==target) return 0;
        int pivot=0,i,lo,hi;
          if(nums[i]>nums[i+1]) break;
        pivot = i;
        if(pivot==n-1) return bsearch(0,n-1,target,nums);
        return target>=nums[0]?bsearch(0,pivot,target,nums):bsearch(pivot+1, n-1,target,nums);
      private int bsearch(int a, int b, int target, int[] nums){
        if(target>nums[b]||target<nums[a]) return -1;
          int mid = (a+b)/2;
          if(target==nums[mid]) return mid;
          else if(target>nums[mid]) a = mid+1;
          else b = mid-1;
        return -1;
    • AC, 0ms

Log in to reply

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