lc033.搜索旋转排序数组 Leetcode binarySearch recursion Dec 04, 2020 题目链接 嗯第一眼就感觉是二分查找法,然后我就一通乱写,就写完了,时间复杂度是O(logN),空间复杂度是O(1)。不过我这个是递归版本的而且好像并没有利用有序这个特性,所以我就又复制了一版用循环实现的。 class Solution: def search1(self, nums: List[int], target: int) -> int: self.ans = -1 left, right = 0, len(nums)-1 self.find(nums, target, left, right) return self.ans def find(self, nums, target, left, right): mid = (left + right) // 2 if nums[mid] == target: self.ans = mid return if left >= right: return self.find(nums, target, left, mid) self.find(nums, target, mid+1, right) def search2(self, nums: List[int], target: int) -> int: if not nums: return -1 l, r = 0, len(nums) - 1 while l <= r: mid = (l + r) // 2 if nums[mid] == target: return mid if nums[0] <= nums[mid]: if nums[0] <= target < nums[mid]: r = mid - 1 else: l = mid + 1 else: if nums[mid] < target <= nums[len(nums) - 1]: l = mid + 1 else: r = mid - 1 return -1 PREVIOUSlc031.下一个排列NEXTlc034.在排序数组中查找元素的第一个和最后一个位置