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.
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, return the minimum element of this array.
题意
假设按照升序排序的数组在预先未知的某个点上进行了旋转。例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] 。请找出其中最小的元素。提示:1 <= nums.length <= 5000-5000 <= nums[i] <= 5000nums 中的所有整数都是 唯一 的nums 原来是一个升序排序的数组,但在预先未知的某个点上进行了旋转样例示例 1:
输入:nums = [3,4,5,1,2]
输出:1
示例 2:
输入:nums = [4,5,6,7,0,1,2]
输出:0
示例 3:
输入:nums = [1]
输出:1
解题
思路:二分查找
本题要明确的一个要点是最小值一定出现在有旋转点的那一侧那么每次搜索我们都需要找到被旋转的那一侧区间,然后比较选择元素小的那一侧区间,那么可以将这两个条件合并nums[mid] < nums[right],当此条件符合时,被旋转区间一定在左侧,小的元素也一定在左侧终止条件:当搜索区间大小为1时,停止搜索,并返回此元素 。public int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
while(left < right){
int mid = left + (right - left) / 2;
if(nums[mid] < nums[right]){
right = mid;
}else{
left = mid + 1;
}
}
return nums[left];
}