- 描述
Follow up for ”Search in Rotated Sorted Array”:
What if duplicates are allowed?
Would this affect the run-time complexity?
How and why?Write a function to determine if a given target is in the array.
public class Solution {
public static int search(int[] arr, int key) {
if(arr == null || arr.length == 0)
return -1;
int low = 0, high = arr.length;
while(low != high) {
int mid = low + (high - low) / 2;
// 主要针对第一个和最后一个元素重复,直接返回第一个
if(arr[low] == key)
return low;
if(arr[mid] == key)
return mid;
if(arr[low] <= arr[mid]) {
if(key >= low && key < arr[mid]) {
high = mid;
}
else {
low = mid + 1;
}
}
else {
if(key > arr[mid] && key <= arr[high-1] ) {
low = mid + 1;
}
else {
high = mid;
}
}
}
return -1;
}
}
网友评论