[LeetCode] Search in Rotated Sorted Array II
https://leetcode.com/problems/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?
Write a function to determine if a given target is in the array.
这道题目,需要注意有重复数字的情况,例如 1111 119 旋转为 119 1 111,那么[left,middle]区域将把9覆盖掉,这样,如果仍然使用之前的方法来做的话,如果target = 9,就直接把9漏掉了。同样,01111 11 旋转为 110 1 111,也会把0的查找漏掉。因此如果遇到nums[left]与nums[middle]相等的情况,我们需要对范围内的整个数组进行遍历来查找。代码如下:
// Author: Jian-xin Zhou class Solution { public: bool search(vector<int>& nums, int target) { int left = 0, right = nums.size() - 1, middle; while (left + 1 < right) { middle = (left + right) >> 1; if (target == nums[middle]) { return true; } // 两者相等时,如果范围取 [left,middle],可能会有问题,例如 1119 1 1111 ,两个1之间夹了较大的9,二分可能会把9排除掉 if (nums[left] == nums[middle] ) { for (int ix = left; ix <= right; ix++) { if (target == nums[ix]) { return true; } } return false; } if (nums[left] < nums[middle]) { if (nums[left] <= target && target < nums[middle]) { right = middle; } else { left = middle; } } if (nums[middle] <= nums[right]) { if (nums[middle] < target && target <= nums[right]) { left = middle; } else { right = middle; } } } if (target == nums[left]) { return true; } if (target == nums[right]) { return true; } return false; } };