Skip to content

Commit

Permalink
Merge pull request #422 from avanimathur/main
Browse files Browse the repository at this point in the history
Solution Day 18 q2: Search in Rotated Sorted Array
  • Loading branch information
bh-g authored Jan 22, 2024
2 parents 076bd8c + fb0312e commit 4fe1ad7
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions Day-18/q2: Search in Rotated Sorted Array/avanimathur--C.cpp
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;
}
};

0 comments on commit 4fe1ad7

Please sign in to comment.