153. Find Minimum in Rotated Sorted Array
1. 题目
153. Find Minimum in Rotated Sorted Array
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.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
2. 题目分析
找旋转数组中最小的元素,并且,旋转数组中不存在相同元素,看过剑指offer的同学就知道,如果存在相同元素,其实里面有坑的,下题讲解加强版存在相同元素的题目。
3. 解题思路
简单暴力的方法是,遍历整个数组,找到最小元素。时间复杂度为O(n);如果作者想要你暴力破解,就不必折腾出回旋数组这种东西了。所以根据回旋数组的特征,找最小值,有没有更高效率的方法呢?
回旋数组其实是分割成两部分,前后部分是相对有序的。所以可以使用二分查找,因为没有重复的,于是很好判断最小值的位置。
当前位置如果小于前面那个数值,则就是最小值了。
4. 代码实现(java)
package com.algorithm.leetcode.binarySearch;
/**
* Created by 凌 on 2019/2/8.
* 注释:153. Find Minimum in Rotated Sorted Array
*/
public class FindMin {
public static void main(String[] args) {
// int[] nums={3,4,5,1,2};
int[] nums={3,4,5,6,0,1,2};
// int[] nums={1};
// int[] nums={1,2};
int result = findMin(nums);
System.out.println(result);
}
public static int findMin(int[] nums) {
if (nums == null){
return -1;
}
if (nums == null){
return -1;
}
int left= 0;
int right = nums.length - 1;
int mid = 0;
while(left < right) {
mid = (left + right) / 2;
//nums[mid] >nums[right] 说明nums[mid] 属于前面的数组
if (nums[mid] > nums[right]) {
left = mid + 1; //可以加1,将查找范围往后推
}else if (nums[mid] < nums[right]) {
//不可以减1, 因为mid可能就是我们要查找的元素
right = mid;
}
}
return nums[left];
}
}