33. Search in Rotated Sorted Array
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.
先用二分法找到最大元素,将数组切分成两个有序数组,再进行二分查找(没有重复数字)
// 二分查找
public int search(int A[], int target) {
if (A == null || A.length <= 0)
return -1;
int n = A.length;
int start = 0, end = n - 1;
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (A[mid] == target) {
return mid;
}
// 中间元素大于最左边元素则左部分为有序数组
else if (A[mid] >= A[start]) {
// 目标位于左部分
if (target >= A[start] && target <= A[mid]) {
end = mid - 1;
}
// 目标位于右部分
else {
start = mid + 1;
}
}
// 中间元素小于最左边元素,则右部分为有序数组
// 说明此时中间元素已经在最小值右侧,不然不会小于最左侧元素
else {
// 目标位于右部分
if (target <= A[end] && target >= A[mid]) {
start = mid + 1;
}
// 目标位于左部分
else {
end = mid - 1;
}
}
}
return -1;
}
81. Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
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
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
当中间值与边缘值相等时,让指向边缘值的指针分别往前移动,忽略掉这个相同点,再用之前的方法判断即可。 这一改变增加了时间复杂度,试想一个数组有同一数字组成{1,1,1,1,1},target=2, 那么这个算法就会将整个数组遍历,时间复杂度由O(logn)升到O(n)
// 二分查找
// 当遇到等于的时候,只能一个个地缩小区间,而不能以log复杂度减小,
//所以在最坏情况下,效率会退化为O(n).
public boolean search(int A[], int target) {
if (A == null || A.length <= 0)
return false;
int n = A.length;
int start = 0, end = n - 1;
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (A[mid] == target) {
return true;
}
// 不同点
// 中间元素大于最左边元素则左部分为有序数组
else if (A[mid] > A[start]) {
// 目标位于左部分
if (target >= A[start]
&& target <= A[mid]) {
end = mid - 1;
}
// 目标位于右部分
else {
start = mid + 1;
}
}
// 中间元素小于最左边元素,则右部分为有序数组
// 说明此时中间元素已经在最小值右侧,不然不会小于最左侧元素
else if (A[mid] < A[start]) {
// 目标位于右部分
if (target <= A[end] && target >= A[mid]) {
start = mid + 1;
}
// 目标位于左部分
else {
end = mid - 1;
}
} else
// 不同点
start++;
}
return false;
}
同类题目:
153.Find Minimum in Rotated Sorted Array
154. Find Minimum in Rotated Sorted Array II