Problem
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.
Idea
由题目知,所给的是一组递增的数组,且不含相同元素,但是最小的元素不一定在首位。
所以第一步,我们需要找到最小的元素的位置,然后就可以用二分查找来进行target数的查找。
思路是清晰的,但是二分查找的代码写得很辣鸡。
Solution
class Solution(object):
def binarySort(self,nums,low,high,target):
pos=(low+high)/2
pre_pos=pos
if pos >len(nums)-1:
pos-=len(nums)
if low > high:
return -1
if target == nums[pos]:
return pos
elif target > nums[pos]:
return self.binarySort(nums,pre_pos+1,high,target)
else:
return self.binarySort(nums,low,pre_pos-1,target)
def findMinIndex(self,nums):
min_index=0
min_num=nums[0]
for i in xrange(1,len(nums)):
min_num=min_num if min_num < nums[i] else nums[i]
if min_num != nums[min_index]:
min_index=i
return min_index
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums)==0:
return -1
min_index=self.findMinIndex(nums)
low=min_index
high=min_index+len(nums)-1
return self.binarySort(nums,low,high,target)
优化:
1. 由于rotated array, 超出范围的index可以用取余解决(i%len(nums)
),即可确保index在范围之内。而不需要这样判断:
if pos >len(nums)-1:
pos-=len(nums)
- 2.