diff --git a/C++/searchInRotatedArrayII.cpp b/C++/searchInRotatedArrayII.cpp new file mode 100644 index 0000000..342c013 --- /dev/null +++ b/C++/searchInRotatedArrayII.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + bool search(vector& nums, int target) { + int left = 0, right = nums.size() - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (nums[mid] == target) { + return true; + } + + // Handle duplicates + if (nums[left] == nums[mid] && nums[mid] == nums[right]) { + left++; + right--; + } else if (nums[left] <= nums[mid]) { // Left half is sorted + if (nums[left] <= target && target < nums[mid]) { + right = mid - 1; // Target is in the left half + } else { + left = mid + 1; // Target is in the right half + } + } else { // Right half is sorted + if (nums[mid] < target && target <= nums[right]) { + left = mid + 1; // Target is in the right half + } else { + right = mid - 1; // Target is in the left half + } + } + } + return false; + } +};