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.
假设按照升序排列的数组在事先未知的某个关键点上旋转。(即0 1 2 4 5 6 7
可能变成4 5 6 7 0 1 2
)。编写一个函数来确定给定的目标是否在数组中。该数组可能包含重复项。
(1)思想1:直接使用find函数,找见则返回true,否则返回false,代码如下:
1 class Solution { 2 public: 3 bool search(vector<int>& nums, int target) { 4 if(find(nums.begin(),nums.end(),target)!=nums.end()) 5 return true; 6 else 7 return false; 8 9 } 10 };
(2)思想2:是33. Search in Rotated Sorted Array的延伸,现在数组中允许出现重复数字,这个也会影响我们选择哪半边继续搜索,由于之前那道题不存在相同值,我们在比较中间值和最右值时就完全符合之前所说的规律:如果中间的数小于最右边的数,则右半段是有序的,若中间数大于最右边数,则左半段是有序的。而如果可以有重复值,就会出现来面两种情况,[3 1 1] 和 [1 1 3 1],对于这两种情况中间值等于最右值时,目标值3既可以在左边又可以在右边,那怎么办么,对于这种情况其实处理非常简单,只要把最右值向左一位即可继续循环,如果还相同则继续移,直到移到不同值为止,其余的处理过程跟33. Search in Rotated Sorted Array一样,代码如下:
1 class Solution { 2 public: 3 bool search(vector<int>& nums, int target) { 4 int begin=0; 5 int end=nums.size()-1; 6 while(begin<=end) 7 { 8 int mid=begin+(end-begin)/2; 9 if(nums[mid]==target) 10 return true; 11 else if(nums[mid]<nums[end]) 12 { 13 if(nums[mid]<target && nums[end]>=target) 14 begin=mid+1; 15 else 16 end=mid-1; 17 } 18 else if(nums[mid]>nums[end]) 19 { 20 if(nums[mid]>target && nums[begin]<=target) 21 end=mid-1; 22 else 23 begin=mid+1; 24 } 25 else 26 end--; 27 } 28 return false; 29 } 30 };