-
Notifications
You must be signed in to change notification settings - Fork 49
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 #437 from Karnankita04/main
Solved Day 18 q2: Search in Rotated Sorted Array #409
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
30 changes: 30 additions & 0 deletions
30
Day-18/Day-18/q2: Search in Rotated Sorted Array/solution.c++
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,30 @@ | ||
class Solution { | ||
public: | ||
int search(vector<int>& nums, int target) { | ||
int low=0, high=nums.size()-1,mid = low+(high-low)/2 ; | ||
|
||
while(low<=high) | ||
{ | ||
if(nums[mid] == target) | ||
return mid ; | ||
|
||
else if(nums[low]<= nums[mid]) // left is sorted | ||
{ | ||
if(target>=nums[low] && target<=nums[mid]) // target lies b/w left half/sorted half | ||
high = mid-1 ; | ||
else // target lies b/w right half | ||
low = mid+1 ; | ||
} | ||
|
||
else // right half is sorted | ||
{ | ||
if(target>=nums[mid] && target<=nums[high]) // target lies b/w right half | ||
low = mid+1 ; | ||
else // target lies b/w left half | ||
high = mid-1 ; | ||
} | ||
mid = low+(high-low)/2 ; | ||
} | ||
return -1 ; | ||
} | ||
}; |