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.
Worst Time Complexity would be O(N).... for example: whole array is [4, 4, 4, 4, 4.....4] then the target is 3.
#include <vector>
#include <iostream>
using namespace std;
bool search(vector<int>& nums, int target) {
if(nums.size() == 0) return false;
int low = 0;
int high = nums.size() - 1;
while(low <= high) {
int mid = low + (high - low) / 2;
if(nums[mid] == target) return true;
if(nums[mid] < nums[high]) {
if(target <= nums[high] && target > nums[mid]) {
low = mid + 1;
} else high = mid - 1;
} else if(nums[mid] > nums[high]) {
if(target >= nums[low] && target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else { high--;}
}
return false;
}
// duplicates in rotated sorted array.
// For example: 4, 4, 5, 6, 1, 2, 3, 4, target is 3.
int main(void) {
vector<int> nums{4, 4, 5, 6, 1, 2, 3, 4};
int target = 2;
bool found = search(nums, target);
cout << found << endl;
}