From d9261daad0da00cc18041cbff9da71a54e6c5584 Mon Sep 17 00:00:00 2001 From: Vivek Date: Sun, 2 Oct 2022 23:18:43 +0530 Subject: [PATCH] Create Q33_SearchInRotatedSortedArray.cpp --- .../Q33_SearchInRotatedSortedArray.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 leetCode Solutions/Q33_SearchInRotatedSortedArray/Q33_SearchInRotatedSortedArray.cpp diff --git a/leetCode Solutions/Q33_SearchInRotatedSortedArray/Q33_SearchInRotatedSortedArray.cpp b/leetCode Solutions/Q33_SearchInRotatedSortedArray/Q33_SearchInRotatedSortedArray.cpp new file mode 100644 index 0000000..64c17bc --- /dev/null +++ b/leetCode Solutions/Q33_SearchInRotatedSortedArray/Q33_SearchInRotatedSortedArray.cpp @@ -0,0 +1,39 @@ +/* +As the array is sorted but rotated, so we figure out +which half of array is sorted, once we know which half of the array is +sorted, we perform a binary search to search for the target. + +Complexity Analysis +TC(Time Complexity): O(log(N)) //Binary Search +SC(Space Complexity): O(1) //Constant Extra Space Used +*/ +class Solution { +public: + int search(vector& nums, int target) { + int n=nums.size(); + int low=0; + int high=n-1; + while(low<=high){ + int mid=(low+high)/2; + if(nums[mid]==target) + return mid; + //Checking if Left half is sorted + if(nums[low]<=nums[mid]) + { + if(nums[low]<=target&&nums[mid]>target) + high=mid-1; + else + low=mid+1; + } + //Checking if Right half is sorted + else + { + if(nums[high]>=target&&nums[mid]