首页 > 代码库 > 81. Search in Rotated Sorted Array II (Array; Divide-and-Conquer)
81. Search in Rotated Sorted Array II (Array; Divide-and-Conquer)
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.
思路:此时可能存在nums[start]=nums[end]或者nums[start]=nums[mid]或者nums[mid]=nums[end]。所以无法用原来方法判断是否正序、右侧rotate、或者左侧rotate。解决方法是,当碰到nums[start]=nums[end]的情况时,end-1,寻找不同元素再进行二分法。
class Solution { public: bool search(vector<int>& nums, int target) { return binarySearch(nums,0,nums.size()-1, target); } bool binarySearch(vector<int>& nums, int start, int end, int target){ if(start==end){ if(nums[start]==target) return true; else return false; } if(nums[start]==nums[end]) return binarySearch(nums,start,end-1,target); //ignore duplicate int mid = start+ ((end-start)>>1); //正序 if(nums[mid]>=nums[start] && nums[mid]<nums[end]){ //mid可能=start,所以>= if(target <= nums[mid]) return binarySearch(nums,start,mid,target); //mid肯定<end,所以至少舍弃了一个 else return binarySearch(nums,mid+1,end,target); //mid+1,至少舍弃了一个 } //右侧rotate else if(nums[mid]>=nums[start] && nums[mid]>=nums[end]){ if(target>=nums[start] && target<=nums[mid]) return binarySearch(nums,start,mid,target); else return binarySearch(nums,mid+1,end,target); } //左侧rotate else{ if(target>=nums[start] || target<=nums[mid]) return binarySearch(nums,start,mid,target); else return binarySearch(nums,mid+1,end,target); } } };
81. Search in Rotated Sorted Array II (Array; Divide-and-Conquer)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。