题目:
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= 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 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.
我的思路:
一个find可以解决的问题,核心思想在于时间复杂度为O(log n) ,对于查找类的问题,时间复杂度为O(log n)一般为二分法。我的代码运行时间还可以,但是有点啰嗦有点长,时间关系暂时不优化.
Runtime: 32 ms(beats 97.3%)
Memory Usage: 14.4 MB(beats 98.7%)
我的解答:
class Solution:
def search(self, nums, target):
ind = 0
if nums[-1] < target < nums[0]:
return -1
elif target >= nums[0]:
while target >= nums[0]:
if target == nums[0]:
return ind
if len(nums) == 1:
return -1
if target >= nums[len(nums)//2] and nums[len(nums)//2] > nums[0]:
ind += len(nums)//2
nums = nums[len(nums)//2:]
else:
nums = nums[:len(nums)//2]
else:
while True:
while target < nums[0]:
if target == nums[0]:
return ind
if len(nums) == 1:
return -1
if nums[len(nums)//2] > nums[0]:
ind += len(nums)//2
nums = nums[len(nums)//2:]
else:
break
if target == nums[0]:
return ind
if len(nums) == 1:
return -1
if target >= nums[len(nums)//2]:
ind += len(nums)//2
nums = nums[len(nums)//2:]
else:
nums = nums[:len(nums)//2]