Rotated Array即旋转数组的定义是:将一个有序数组的某个位置k之后的子数组移动到数组前面,是原数组的前半部分和后半部分都是有序的。例如:0,1,2,3,4,5,6,取k=4,则旋转之后的数组为:4,5,6,0,1,2,3.
leetcode[https://leetcode.com/]上关于rotated array的题目一共有四题:
33.Search in Rotated Sorted Array 31.0% Hard
81.Search in Rotated Sorted Array II 32.4% Medium
153.Find Minimum in Rotated Sorted Array 37.5% Medium
154.Find Minimum in Rotated Sorted Array II 35.3% Hard
其中33和81都是查找,153和154都是返回数组的最小值,而81和154都是允许数组有重复元素。其实在leetcode上提交顺序扫描的方法也能AC,但是时间复杂度O(n),如果要求时间复杂度为O(lgn)呢?那就需要用二分查找的方法了。本文给出的代码及思路都是基于二分查找。下面依次给出这四道题的解题思路:
对于旋转后的数组主要有三种形式:
不变k=0:01234567
转小部分k>4: 67012345
转大部分k<4:34567012
为什么分这三种情况呢?因为二分查找每次比较时中位数,所以我们需要找到中位数哪边的是顺序数组,这样处理起来就比较方便了。
由于返回最小值是查找key值的特殊情况,所以我们先从153开始:
153. Find Minimum in Rotated Sorted Array
Suppose a sorted array 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.
AC代码:
package CodeJava_Leet;
/**
* Created by Yechengpeng on 2016-08-14.
*/
//153. Find Minimum in Rotated Sorted Array
public class MinRotatedArray {
public static void main(String[] args) {
int[] nums = {
2,1};
System.out.println(findMin(nums));
}
public static int findMin(int[] nums) {
int low = 0, high = nums.length-1;
while(low <= high){