题目
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
你可以假设数组中不存在重复元素。
示例 1:
输入: [3,4,5,1,2]
输出: 1
示例 2:
输入: [4,5,6,7,0,1,2]
输出: 0
解题思路
The minimum number must be at the disordered part, or at the leftest. So every time we do a binary search, we discard the ordered part, and finally we will converge to the minimum number.
Time Complexity:
o
(
log
n
)
o(\log n)
o(logn)
Space Complexity:
o
(
1
)
o(1)
o(1)
Or another method, every time we discard the ordered and larger part, and we could converge directly to the point.
Or another method, we discard the larger part
代码
Discard the ordered part
class Solution:
def findMin(self, nums: List[int]) -> int:
res = nums[0]
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[left] <= nums[mid]:
res = min(res, nums[left])
left = mid + 1
else:
res = min(res, nums[mid])
right = mid
return min(res, nums[left])
Discard the ordered & larger part
class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] < nums[right]:
right = mid
else:
left = mid + 1
return nums[left]
Discard the larger part
class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
elif nums[mid] < nums[right]:
right = mid
return nums[left]