题目链接: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.
思路:和上题思路差不多,分析应该搜索左边还是右边。每次二分有四种情况:
1. nums[mid] = target,则可以返回mid
2. nums[mid] < nums[right],说明在[mid, right]区间是右边递增的区间,然后判断target是否在这个区间内
1)如果nums[mid] < target <= nums[right],说明target在右边区间里,则left = mid + 1;
2)否则在左边区间里,搜索左边区间,right = mid - 1;
3. nums[mid] > nums[right],说明[elft, mid]区间是在左边的递增区间,然后判断target是否在这个左边区间里
1)如果nums[left] <= target < nums[mid],说明target在这个区间里,则使right = mid - 1;
2)否则说明target在[mid, right]的不规则区间里,搜索右边区间,则使left = mid + 1;
4. nums[mid] == nums[right],这种情况并不知道搜索哪一边,因为nums[right] != target,此时可以抛弃nums[right],搜索[left, right-1]的区域
然后考虑边界条件:
如果数组长度为1,则left = right,mid = left=right,如果nums[mid] = target,则直接返回,否则会进入条件3,然后循环结束,返回-1;
代码如下:
class Solution { public: bool search(vector<int>& nums, int target) { int len = nums.size(), left = 0, right = len-1; if(len == 0) return false; while(left <= right) { int mid = (left + right)/2; if(target == nums[mid]) return true; if(nums[mid] < nums[right])// { if(target > nums[mid] && target <= nums[right])//搜索右边有序数组 left = mid + 1; else right = mid -1; } else if(nums[mid] > nums[right]) { if(target >= nums[left] && target < nums[mid])//搜索左边有序数组 right = mid -1; else left = mid + 1; } else right--; } return false; } };参考:http://bangbingsyb.blogspot.com/2014/11/leetcode-search-in-rotated-sorted-array.html