题目: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.
思路:
题目说有重复数字,但是用之前的代码不影响的,只需要修改为bool变量就行。
之前的-1改成false,之前的返回某一位变成存在。即true,本质上变得更加简单。
很快accepted!
参考:Search in Rotated Sorted Array
代码:
class Solution { public: //https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ bool search(vector<int>& nums, int target) { int len=nums.size(); //找到第一个变小的值下,写一个新函数 int left=0,right=len-1; int f=findFirstBig(nums); if(f==0){ return binareSearch(f,len,nums,target); }else{ if(nums[f-1]>=target){ left= binareSearch(0,f-1,nums,target); if(left!=false) return left; } if(nums[f]<=target){ right= binareSearch(f,len-1,nums,target); if(right!=false) return right; } return false; } } //二分查找 int binareSearch(int i,int j,vector<int>& nums,int target){ while(i<=j){ int mid=(i+j)/2; if(nums[mid]==target){ return true; } if(nums[mid]<target){ i=mid+1; } if(nums[mid]>target){ j=mid-1; } } if(i>j){ return false; } } //找到第一个减小的数值 int findFirstBig(vector<int>& nums){ int len=nums.size(); for(int i=0;i<len;i++){ if(i>0&&nums[i]<nums[i-1]){ return i; } } return 0; } };