版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82346432
假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。
你需要找到其中最小的元素。
你可以假设数组中不存在重复的元素。
样例
给出[4,5,6,7,0,1,2] 返回 0
注意事项
You may assume no duplicate exists in the array.
解题思路1:
直接使用treeSet,返回第一个值就是最小值。
public class Solution {
/**
* @param nums: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] nums) {
// write your code here
TreeSet<Integer> treeSet = new TreeSet<>();
for(int num : nums){
treeSet.add(num);
}
return treeSet.first();
}
}
解题思路2:
看到有序数组就想到二分查找。首先要判断这个有序数组是否旋转了,通过比较第一个和最后一个数的大小,如果第一个数小,则没有旋转,直接返回这个数。如果第一个数大,就要进一步搜索。
我们定义left和right两个指针分别指向开头和结尾,还要找到中间那个数,然后和right指的数比较,如果中间的数>=nums[r],表明mid落在了前半段区间,二分查找右半段数组,反之查找左半段。终止条件是当左右两个指针相邻,返回小的那个。
public class Solution {
/**
* @param nums: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] nums) {
// write your code here
if(nums[0] < nums[nums.length-1])
return nums[0];
int l = 0;
int r = length-1;
while(l<r){
int mid = (r-l)/2+l;
if(nums[mid] >= nums[r])
l = mid + 1;
else
r = mid;
}
return Math.min(nums[l] , nums[r]);
}
}