Search In Shifted Sorted Array II
Given a target integer T and an integer array A, A is sorted in ascending order first, then shifted by an arbitrary number of positions.
For Example, A = {3, 4, 5, 1, 2} (shifted left by 2 positions). Find the index i such that A[i] == T or return -1 if there is no such index.
Assumptions
There could be duplicate elements in the array.
Return the smallest index if target has multiple occurrence.
Examples
A = {3, 4, 5, 1, 2}, T = 4, return 1
A = {3, 3, 3, 1, 3}, T = 1, return 3
A = {3, 1, 3, 3, 3}, T = 1, return 1
Corner Cases
What if A is null or A is of zero length? We should return -1 in this case.
思路:
先把所有的 array[mid]在target右边的情况全列出来,并更新right
当 array[mid] == array[0] 时我们不清楚mid是在target的右边还是左边,就默认把left +=1右移逐个检查, 把left, right 中间的searching space往中间缩小, 有可能arr[mid] == arr[0], 并且mid是在arr右端, 而arr[0] 在左端,要往中间缩小搜索范围
else默认左移right
Time: O(n) worest case, average case: O(logn)
Last updated