L62 Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,0 1 2 4 5 6 7
might become4 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.
Example
For[4, 5, 1, 2, 3]
andtarget=1
, return2
.
For[4, 5, 1, 2, 3]
andtarget=0
, return-1
.
O(logN) time
9章的2分模板T:O(logn),S:O(1)。主要是要半段哪一半有序,然后在那里面找。通过判断target在有序一半或在无序的一半来移动下标。
If duplicate exist, you need to check if A[mid]==A[left]
is so, need to check if A[right]!=A[mid]
if so, search right
else search both side
Last updated