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.

分析

从左向右扫描,扫描到的第一个逆序的位置,肯定是原始数组中第一个元素,时间复杂度O(n)

不过本题依旧可以用二分查找,最关键的是要判断那个“断层”是在左边还是右边。

  • 若A[mid] < A[right],则区间[mid,right]一定递增,断层一定在左边
  • 若A[mid] > A[right],则区间[left,mid]一定递增,断层一定在右边
  • nums[mid] == nums[right],这种情况不可能发生,因为数组是严格单调递增的,不存在重复元素

    代码

  1. // Find Minimum in Rotated Sorted Array
  2. // 时间复杂度O(logn),空间复杂度O(1)
  3. public class Solution {
  4. public int findMin(int[] nums) {
  5. int left = 0;
  6. int right = nums.length - 1;
  7. while (left < right) {
  8. int mid = left + (right - left) / 2;
  9. if (nums[mid] < nums[right]) {
  10. right = mid;
  11. } else {
  12. left = mid + 1;
  13. }
  14. }
  15. return nums[left];
  16. }
  17. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/search/find-minimum-in-rotated-sorted-array.html