153. Find Minimum in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

Find the minimum element.

You may assume no duplicate exists in the array.

Example 1:

Input:[3,4,5,1,2] 

Output:1

Example 2:

Input:[4,5,6,7,0,1,2]

Output:0

Thoughts:

  1. Binary Search:
    1. 1st method : To find the minimum, use the nums[mid] to compare with nums[right]:
    2. 2nd method: To compare with nums[left] and at the end compare the found result with start and end value (since this method would "assume there is a pivot")

Code1:

class Solution {
    public int findMin(int[] nums) {
        int left = 0, right = nums.length - 1;

        while (left < right){
            int mid = left + (right - left >> 1);
            if (nums[mid] > nums[right]){
                left = mid + 1;
            }
            else 
                right = mid;
        }

        return nums[left];
    }
}

Code2:

class Solution {
   //binary search
    public int findMin(int[] nums){
        int i =0;
        int j=nums.length-1;
        int start=nums[i];
        int end=nums[j];
        while(i+1<j) {
            int mid = i + (j - i) / 2;
            if (nums[mid] > nums[i])
                i = mid;
            else 
                j = mid;
        }


         // min in (nums[i] , nums[j], start)
         return Math.min(Math.min(nums[i], nums[j]),start);

        }
}

results matching ""

    No results matching ""