您的位置:首页 > 汽车 > 新车 > 企业邮箱域名怎么填写_上网行为管理_苏州关键词优化怎样_seo索引擎优化

企业邮箱域名怎么填写_上网行为管理_苏州关键词优化怎样_seo索引擎优化

2025/1/8 0:11:59 来源:https://blog.csdn.net/weixin_44245188/article/details/143184148  浏览:    关键词:企业邮箱域名怎么填写_上网行为管理_苏州关键词优化怎样_seo索引擎优化
企业邮箱域名怎么填写_上网行为管理_苏州关键词优化怎样_seo索引擎优化

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

Example 3:

Input: nums = [1], target = 0
Output: -1

Constraints:

1 <= nums.length <= 5000
-104 <= nums[i] <= 104
All values of nums are unique.
nums is an ascending array that is possibly rotated.
-104 <= target <= 104

https://leetcode.cn/problems/search-in-rotated-sorted-array/description/

方法一:两次二分

class Solution:# 153. 寻找旋转排序数组中的最小值def findMin(self, nums: List[int]) -> int:left, right = -1, len(nums) - 1  # 开区间 (-1, n-1)while left + 1 < right:  # 开区间不为空mid = (left + right) // 2if nums[mid] < nums[-1]:  # 蓝色right = midelse:  # 红色left = midreturn right# 有序数组中找 target 的下标def lower_bound(self, nums: List[int], left: int, right: int, target: int) -> int:while left + 1 < right:  # 开区间不为空mid = (left + right) // 2# 循环不变量:# nums[left] < target# nums[right] >= targetif nums[mid] < target:left = mid  # 范围缩小到 (mid, right)else:right = mid  # 范围缩小到 (left, mid)return right if nums[right] == target else -1def search(self, nums: List[int], target: int) -> int:i = self.findMin(nums)if target > nums[-1]:  # target 在第一段return self.lower_bound(nums, -1, i, target)  # 开区间 (-1, i)# target 在第二段return self.lower_bound(nums, i - 1, len(nums), target)  # 开区间 (i-1, n)

方法二:一次二分

class Solution:def search(self, nums: List[int], target: int) -> int:def is_blue(i: int) -> bool:x = nums[i]if x > nums[-1]:return target > nums[-1] and x >= targetreturn target > nums[-1] or x >= targetleft, right = -1, len(nums) - 1  # 开区间 (-1, n-1)while left + 1 < right:  # 开区间不为空mid = (left + right) // 2if is_blue(mid):right = midelse:left = midreturn right if nums[right] == target else -1

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com