Suppose a sorted array 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.
思路分析:考察二分查找,比较简单。找不到返回l,注意停止二分的条件是l<=r,=不要掉。
AC Code
public class Solution {
public int searchInsert(int[] A, int target) {
//02:22
if(A.length == 0 || A == null) return 0;
int l = 0;
int r = A.length - 1;
while(l <= r){
int m = (l + r) / 2;
if(A[m] > target) {
r = m -1;
} else if(A[m] < target){
l = m + 1;
} else {
return m;
}
}
return l;
//02:29
}
}