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.
The array may contain duplicates.
Given [4,4,5,6,7,0,1,2] return 0
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 0; int left = 0; int right = num.length - 1; while(left < right - 1){ if(num[left] < num[right]) return num[left]; while(left < right - 1 && num[left] == num[left + 1]) left++; while(left < right - 1 && num[right] == num[right - 1]) right--; int mid = left + (right - left) / 2; if(num[left] <= num[mid]) left = mid + 1; else right = mid; } return Math.min(num[left], num[right]); } }
时间: 2024-10-17 21:29:11