153. Find Minimum in Rotated Sorted Array
题目描述 假设按照升序排序的数组,在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 请找出其中最小的元素。(假设数组中不存在重复元素) 例子 Example 1: Input: [3,4,5,1,2] Output: 1 Example 2: Input: [4,5,6,7,0,1,2] Output: 0 思想 若旋转了,则num[l] > num[r];否则未旋转,直接返回num[l]。 当nums[mid] > nums[r]时,mid在未旋转部分,取l = mid + 1; 否则,mid在旋转部分,取r = mid;class class Solution: def findMin(self, nums: List[int]) -> int: l,r=0,len(nums)-1 while l<r and nums[l] >nums[r]: mid=(l+r)>>1 if nums[mid]>nums[r]: l=mid+1 else: r=mid return nums[l]162. Find Peak Element 峰值元素是大于其邻居的元素。
给定一个输入数组nums,其中nums [i]≠nums [i + 1],找到一个峰值元素并返回其索引。
该阵列可能包含多个峰值,在这种情况下,将索引返回到任何一个峰值都很好。
你可以想象nums [-1] = nums [n] =-∞。
Example 1: Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1,2,1,3,5,6,4] Output: 1 or 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. class Solution: def findPeakElement(self, nums: List[int]) -> int: length=len(nums) l,r=0,length-1 while l<r : mid=(l+r)>>1 if nums[mid]>nums[mid+1]: r=mid else: l=mid+1 return l