您的位置:首页 > 其它

[Leetcode] 81. Search in Rotated Sorted Array II 解题报告

2017-02-09 09:21 645 查看
题目

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、先利用O(n)的时间复杂度扫描数组,得到pivot的索引,然后分别在pivot的左边和右边利用二分法进行查找。这种方法的时间复杂度确定为O(n)。

2、设计适用于旋转有序数组的二分法。每次二分有四种情况需要考虑:

      1)中间的数等于target,那么直接返回结果;

      2)中间的数小于最右边的数,这说明右边区间是递增的区间,然后判断target是否在这个区间之内:

            a)如果target的大小介于中间的数和最右边的数,那么说明target如果存在则一定会在右边区间,此时更新左边界;

            b)否则target只可能存在于左边区间中,则更新右边界;

      3)中间的数大于最右边的数,这说明左区间是递增区
4000
间,然后判断target是否在这个区间之中:

            a)如果target的大小介于最左边的数和中间的数,说明target如果存在则一定会在左边区间,此时更新右边界;

            b)否则target只能存在于右边区间中,则更新左边界。

      4)中间的数等于最右边的数。这种情况无法确定要搜索哪一边。此时只能采用最保守的方法:抛弃最右边的数。

      在最坏情况下,思路2的时间复杂度会退化到O(n),但通常情况下其时间复杂度是O(logn)。

      常规二分查找法往往都是比较中间数和target的大小,但是对于旋转数组而言,恰恰不能用这种方法,因为即使我们比较了,也不知道接下来往哪个方向走。一个比较好的办法是比较中间数和边界数的大小,这样可以首先确定哪个区间是严格递增的,然后再根据子区间是否单调递增,采用常规二分查找,或者递归调用本函数。

代码

class Solution {
public:
bool search(vector<int>& nums, int target) {
if (nums.size() == 0) {
return false;
}
return binarySearch(nums, target, 0, nums.size() - 1);
}
private:
bool binarySearch(vector<int> &nums, int target, int left, int right) {
if (left > right) {
return false;
}
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return true;
}
else if (nums[mid] < nums[right]) {     // right side is increasing
if (nums[mid] < target && target <= nums[right]) {
return binarySearch(nums, target, left + 1, right);
}
else {
return binarySearch(nums, target, left, right - 1);
}
}
else if (nums[mid] > nums[right]) {     // left side is increasing
if (nums[left] <= target && target < nums[mid]) {
return binarySearch(nums, target, left, right - 1);
}
else {
return binarySearch(nums, target, left + 1, right);
}
}
else {
return binarySearch(nums, target, left, right - 1);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: