问题描述
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.
The array may contain duplicates.
从旋转
数组中找到最小值,数组包含重复元素。
举个例子:
Input: [2,2,2,0,1]
Output: 0
类似题:
[81] Search in Rotated Sorted Array II{:target=”_blank”}
解法1
老规矩,把末尾与开头相同的元素去除就行。
来看下实现:
class Solution {
public int findMin(int[] nums) {
int n = nums.length;
int R = n - 1;
while (R > 0 && nums[R] == nums[0]){
R--;
}
int l = 0, r = R;
while (l < r){
int mid = l + r + 1 >> 1;
if (nums[mid] >= nums[0]) l = mid;
else r = mid - 1;
}
return l == R ? nums[0] : nums[l + 1];
}
}
Enjoy it !