*153. Find Minimum in Rotated Sorted Array[Medium]
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.
You must write an algorithm that runs in O(log n) time.
Constraints:
- n == nums.length
- 1 <= n <= 5000
- -5000 <= nums[i] <= 5000
- All the integers of nums are unique.
- nums is sorted and rotated between 1 and n times.
Example
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
思路
二分查找变体,虽然被旋转了,但子串还是有序的,通过中位来判断
题解
public int findMin(int[] nums) {
int left, right, mid, min;
left = 0;
right = nums.length - 1;
min = nums[left];
while (left <= right) {
// 如果当前最右比最左大,那说明这一段子串是顺序的,直接取最左
if (nums[right] > nums[left]) {
min = Math.min(min, nums[left]);
break;
}
mid = (left + right) / 2;
min = Math.min(nums[mid], min);
// 如果当前中位比最右大,那说明右边这段应该是被旋转了,是属于小的那一部分,就切到右半边来
if (nums[mid] > nums[right])
left = mid + 1;
else
// 如果当前中位比最右小,那没有旋转,左边是小的部分,切到左半边
right = mid - 1;
}
return min;
}

浙公网安备 33010602011771号