Sunday, October 1, 2017

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.
Solution:
public int findMin(int[] nums) {
      return findMinRec(nums, 0, nums.length-1);
    }
    
    public int findMinRec(int[] a, int start, int end) {
        while(start<end) {
            if(a[start]<a[end])
                return a[start];
            int mid = start+(end-start)/2;
            if(a[start]<=a[mid]) {
                start=mid+1;
            } else {
                end=mid;
            } 
        }
        return a[start];
    }

No comments:

Post a Comment