您的位置:首页 > 其它

leetcode 81. Search in Rotated Sorted Array II

2018-03-09 14:41 435 查看

题目

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.

解析

class Solution {
public boolean search(int[] a, int target) {
if (a.length == 0 || a== null)
return false;
int lo = 0, hi = a.length - 1;
while (lo < hi) {
int mid = (lo + hi) >> 1;
if (a[mid] == target) {
return true;
} else if (a[mid] > a[hi]) {
//考虑单调的一边
if (a[mid] > target && target >= a[lo]) {
hi = mid;
} else {
lo = mid + 1;
}
} else if (a[mid] < a[hi]) {
if (a[mid] < target && a[hi] >= target) {
lo = mid + 1;
} else {
hi = mid;
}
} else {
hi--;
}
}
return a[lo] == target ? true : false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: