刷题笔记
153. Find Minimum in Rotated Sorted Array
题目
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], …, a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], …, a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array.
思路
- 这道题,与经典的binarysearch相比,不同点在于判断条件,那么关键点就是找出缩小判断范围的判断条件。
- 要找出最小元素,最小元素的特点是比最右边的数小,而利用这一点就可以设置判断条件。如果一个数比右边数小,那么这个数仍然属于判断范围,将右侧边界缩小;如果它比右边数大,那么它是左侧array的数,可以把包括这个数在内的抛弃出判断范围;如果等于右边的数,则已经是最后一个数,那么返回这个数就是最小数(因为最后一定会有一个最小值)。
代码实现
class Solution {
public int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
if (nums.length == 0) return 0;
int min = binarySearchMin (nums, left, right);
return min;
}
private int binarySearchMin (int[] nums, int left, int right) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[right]) {
right = mid;
} else if (nums[mid] == nums[right]) {
return nums[mid];
} else {
left = mid + 1;
}
}
return -1;
}
}