Search in Rotated Sorted Array
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
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
class Solution { public: int search(vector<int>& nums, int target) { if(nums.size()==0) return -1; int low=0,high=nums.size()-1; while(low<=high) { int mid=low+(high-low)/2; if(target==nums[mid]) { return mid; } if(nums[mid]<nums[low]) { if(target>nums[mid]&&target<=nums[high]) { low=mid+1; }else { high=mid-1; } }else if(nums[mid]>=nums[low]) { if(target>=nums[low]&&target<nums[mid]) { high=mid-1; }else { low=mid+1; } } } return -1; } };
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
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.
class Solution { public: bool search(vector<int>& nums, int target) { int n=nums.size(); if(n==0) return false; int low=0,high=n-1; int mid=0; while(low<=high) { mid=low+(high-low)/2; if(nums[mid]==target) return true; if(nums[mid]==nums[low]&&nums[mid]==nums[high]) { low++; high--; } else if(nums[low]<=nums[mid]) { if(target>=nums[low]&&target<nums[mid]) high=mid-1; else low=mid+1; }else { if(target<=nums[high]&target>nums[mid]) low=mid+1; else high=mid-1; } } return false; } };