-
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 #422 from avanimathur/main
Solution Day 18 q2: Search in Rotated Sorted Array
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
Day-18/q2: Search in Rotated Sorted Array/avanimathur--C.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,44 @@ | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
|
||
class Solution { | ||
public: | ||
|
||
int search(const vector<int>& nums, int target) { | ||
|
||
if (nums.empty()) { | ||
return -1; | ||
} | ||
|
||
int left = 0, right = nums.size() - 1; | ||
while (left < right) { | ||
int mid = (left + right) / 2; | ||
|
||
if (nums[mid] > nums[right]) { | ||
left = mid + 1; | ||
} else { | ||
right = mid; | ||
} | ||
} | ||
|
||
int pivot = left; | ||
|
||
left = 0; | ||
right = nums.size() - 1; | ||
|
||
while (left <= right) { | ||
int mid = (left + right) / 2; | ||
int midVal = nums[(mid + pivot) % nums.size()]; | ||
|
||
if (midVal == target) { | ||
return (mid + pivot) % nums.size(); | ||
} else if (midVal < target) { | ||
left = mid + 1; | ||
} else { | ||
right = mid - 1; | ||
} | ||
} | ||
|
||
return -1; | ||
} | ||
}; |