Skip to content

Commit

Permalink
Solved Day 18 q2: Search in Rotated Sorted Array SnowScriptWinterOfCo…
Browse files Browse the repository at this point in the history
  • Loading branch information
Karnankita04 committed Jan 18, 2024
1 parent f121f12 commit d790acc
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Day-18/Day-18/q2: Search in Rotated Sorted Array/solution.c++
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 ;
}
};

0 comments on commit d790acc

Please sign in to comment.