Leetcode Find Minimum in Rotated Sorted Array I and II

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode Find Minimum in Rotated Sorted Array I and II相关的知识,希望对你有一定的参考价值。

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.

 

在任何一个sublist中,如果头元素大于尾元素,那么这个minimum一定在这个sublist中间的某一个位置。可以用二分法找到这个元素,复杂度是O(logN)。本题O(N)的算法也可以通过OJ,思路就是最简答的从头元素往后比,直到出现 nums[i] > nums[i+1]的情况,那么nums[i+1]就是Minimum element。

 

 1 class Solution(object):
 2     def findMin(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         n = len(nums)
 8         left = 0
 9         right = n-1
10         while left < right:
11             mid = (left+right)//2
12             if nums[mid] > nums[right]:
13                 left = mid + 1
14             else:
15                 right = mid
16         return nums[left]
17         

 

以下引用来自: http://bangbingsyb.blogspot.com/2014/11/leecode-find-minimum-in-rotated-sorted.html

和Search in Rotated Sorted Array II这题换汤不换药。同样当A[mid] = A[end]时,无法判断min究竟在左边还是右边。
 
3 1 2 3 3 3 3 
3 3 3 3 1 2 3
 
但可以肯定的是可以排除A[end]:因为即使min = A[end],由于A[end] = A[mid],排除A[end]并没有让min丢失。所以增加的条件是:
 
A[mid] = A[end]:搜索A[start : end-1]
 
 1 class Solution(object):
 2     def findMin(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         n = len(nums)
 8         left = 0
 9         right = n-1
10         while left < right:
11             mid = (left+right)//2
12             if nums[mid] > nums[right]:
13                 left = mid + 1
14             elif nums[mid] < nums[right]:
15                 right = mid
16             else:
17                 right -= 1
18         
19         return nums[left]

 


以上是关于Leetcode Find Minimum in Rotated Sorted Array I and II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode153:Find Minimum in Rotated Sorted Array

Find Minimum in Rotated Sorted Array leetcode

#Leetcode# 154. Find Minimum in Rotated Sorted Array II

**Leetcode 153. Find Minimum in Rotated Sorted Array

[LeetCode] 153. Find Minimum in Rotated Sorted Array

LeetCode-153-Find Minimum in Rotated Sorted Array