Find Minimum in Rotated Sorted Array II 160

Question

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.

Notice

The array may contain duplicates.

Example

Given [4,4,5,6,7,0,1,2] return 0.

Solution

这道题和I不一样,因为有重复元素,所以不能用二分查找的方法(如1,1,-1,1就会有问题),只能遍历所有元素求最小值。

代码如下:

 public class Solution {
    /**
     * @param num: a rotated sorted array
     * @return: the minimum number in the array
     */
    public int findMin(int[] num) {
        // write your code here
        if (num == null || num.length == 0){
            return -1;
        }
        int mini = 0;

        for(int i = 0; i < num.length; i++){
            if(num[i] < num[mini]){
                mini = i;
            }
        }

        return num[mini];
    }
}

results matching ""

    No results matching ""