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.
思路
因为有duplicates,所以没法用二分法做。因为你在碰到一个数的时候没法知道到底是往左还是往右搜索。只能for循环过一遍。
Code
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.length == 0) { return num[0]; } int min = Integer.MAX_VALUE; for (int n : num) { min = Math.min(min, n); } return min; } }