162. 寻找峰值 - 力扣(LeetCode)
没二分,数组头尾分别插入最小值和最大值,比较num[i-1]<num[i]>num[i+1]
class Solution:def findPeakElement(self, nums: List[int]) -> int:if not nums:return Nonemax_num,min_num=min(nums)-1,min(nums)-1new_nums=[min_num]+nums+[max_num]left,right=1,len(nums)for i in range(left,right+1):if new_nums[i-1]<new_nums[i] and new_nums[i]>new_nums[i+1]:return i-1
167. 两数之和 II - 输入有序数组 - 力扣(LeetCode)
头+尾大于目标尾减,小于目标头加
class Solution:def twoSum(self, numbers: List[int], target: int) -> List[int]:if not numbers:return Noneleft,right=0,len(numbers)-1while left<right:if numbers[left]+numbers[right]>target:right-=1elif numbers[left]+numbers[right]<target:left+=1else:return [left+1,right+1]
209. 长度最小的子数组 - 力扣(LeetCode)
快慢指针
慢指针指向窗口头,快指针向前走,计算快慢指针之间数据和
- 和小于目标值,快指针向前走
- 和大于等于目标值,快指针不动,记录窗口长度,和减去当前慢指针数据,慢向前走
class Solution:def minSubArrayLen(self, target: int, nums: List[int]) -> int:if not nums: return 0slow,fast,sums=0,0,0re=len(nums)+1while slow<=fast:if sums<target:if fast<len(nums):sums+=nums[fast]fast+=1else:breakelse:re=min(re,fast-slow)sums-=nums[slow]slow+=1if re==len(nums)+1:return 0return re
240. 搜索二维矩阵 II - 力扣(LeetCode)
按行进行二分,应该还有简单的方法,容我思考思考
class Solution:def help(self,nums,target):if not nums:return Falseleft,right=0,len(nums)while left<right:middle=int((left+right)/2)if nums[middle]==target:return Trueelif nums[middle]>target:right=middleelse:left=middle+1return Falsedef searchMatrix(self, matrix: List[List[int]], target: int) -> bool:if not matrix:return Falseleft,right=0,len(matrix)for i in range(right):if self.help(matrix[i],target):return Truereturn False