leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

Better solution for Find Minimum In Rotated Sorted Array - Java

Open SleeplessChallenger opened this issue 2 years ago • 0 comments

Actually, in this problem we can simplify the logic:

  1. if mid value < hi value -> search to the left inclusive mid. Because we don't need to look at any number to the right, but current mid value should be kept as it can be an answer.
  2. else case. More precisely, if rightmost value is not bigger - it means it will be smaller as only unique values are presented. And it means that to the left there will be the values preceding to the mid => go right as we have deflection point to the right

Code

class Solution {
    public int findMin(int[] nums) {
        // at least 1 element in nums. Elements are unique. [5,0,1,2,4]; [2,1]
        int lo = 0;
        int hi = nums.length - 1;

        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;

            if (nums[mid] < nums[hi]) {
                /*
                go left and keep curr mid as it may be our answer
                we are guaranteed that min will be there as left
                is smaller -> deflection somewhere to the left
                */
                hi = mid;
            } else {
                // go right
                lo = mid + 1;
            }
        }

        return nums[lo];
    }
}

SleeplessChallenger avatar Mar 18 '23 18:03 SleeplessChallenger