-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #29 from vivek-dhiman/main
Added solution to Q33 of Leetcode in cpp
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
leetCode Solutions/Q33_SearchInRotatedSortedArray/Q33_SearchInRotatedSortedArray.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<int>& 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]<target) | ||
low=mid+1; | ||
else | ||
high=mid-1; | ||
} | ||
} | ||
return -1; //if target not found | ||
} | ||
}; |