Leetcode 33. Search in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e.,
[0,1,2,4,5,6,7]
might become[4,5,6,7,0,1,2]
).You are given a target value to search. If found in the array return its index, otherwise return
-1
.You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
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
要求时间复杂度是O(logn)因此确定 应该是在原数组上操作,可以用一个二分法的变式来写,代码如下:
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n = len(nums)
if n == 0:
return -1
if n == 1 :
if nums[0] == target:
return 0
else:
return -1
pivot = n//2
output = 0
while n > 0:
if nums[pivot] == target:
output = output + pivot
break
elif nums[pivot] > target:
if(nums[0] <= target and nums[0] < nums[pivot])\
or (nums[0] >= target and nums[0] > nums[pivot]):
nums = nums[0:pivot]
else:
nums = nums[pivot+1:]
output += pivot+1
elif nums[pivot] < target:
if(nums[-1] >= target and nums[-1] > nums[pivot])\
or (nums[-1] <= target and nums[-1] < nums[pivot] ):
nums = nums[pivot+1:]
output += pivot+1
else:
nums = nums[0:pivot]
n = len(nums)
pivot = n//2
if len(nums) == 0:
return -1
else:
return output
beat60+%
发现如果不用替换数组的方法直接改指针或者index速度会更快:
代码如下:
class Solution(object):
def search(self, A, target):
l,r = 0,len(A)-1
while l <= r:
m = (l+r)//2
if A[m] == target:
return m
else:
if A[m] < A[r]:
if A[m] <= target <=A[r]:
l = m +1
else:
r = m -1
else:
if A[l]<= target <= A[m]:
r = m -1
else:
l = m + 1
return -1