Sunday, January 11, 2015

LeetCode 153: Find Minimum in Rotated Sorted Array

Suppose a sorted array 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.
public class Solution {
    public int findMin(int[] num) {
        // Note: The array may not rotate.
        int n = num.length;
        
        if (n == 0)
            return 0;
        
        if (n == 1)
            return num[0];
        
        // If the array didn't rotate, return the first element;
        // Otherwise return the skip element.
        for (int i = 0; i < n-1; i++)
            if (num[i] > num[i+1])
                return num[i+1];
        
        return num[0];
    }
}

No comments:

Post a Comment