Leetcode算法题 153
题名:Find Minimum in Rotated Sorted Array
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/?tab=Description
题目:
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.
题目解读:
对于一个有序数组,将其在某一节点位置进行旋转,对于新的数组找出最小元素
解题思路:
思路一:常规解法,对数组进行排序,使用升序排列,获取最小元素,时间复杂度O(n)
思路二:二分查找法,查找数组中间元素,将其与数组右端点进行对比,如果中间值大于右节点的值,则将右节点的指针指向中间节点-1, 否则将左节点指向中间节点+1
思考:二分查找的思想在很多题目中都有体现,主要包括几个部分
1、设定左右指针,设置中间指针
2、比较中间值和目标值,根据结果调整左右指针的位置
3、设置循环条件保证左右指针交汇或者错开
Python代码如下
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left = 0
right = len(nums) - 1
ans = nums[0]
while left <= right:
mid = (left + right) / 2
if nums[mid]<nums[right]:
right = mid-1
else:
left = mid+1
ans = min(ans, nums[mid])
return ans