day 40: 153-find-minimum-in-rotated-sorted-array

This commit is contained in:
Kaushik Narayan R 2023-11-19 14:43:04 -07:00
parent 860fa91880
commit 5f1e2efa9e
3 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<int> nums = {7, -1, 0, 1, 2, 3, 4, 5, 6};
int answer = -1;
Solution soln;
cout << "Found minimum correctly? " << soln.test(nums, answer) << endl;
return 0;
}

View File

@ -0,0 +1,31 @@
#include "soln.hpp"
int Solution::findMin(vector<int> &nums)
{
int low = 0, high = nums.size() - 1, mid;
while (low < high)
{
// current subarray is unrotated
if (nums[high] > nums[low])
{
return nums[low];
}
mid = (low + high) / 2;
// left half
if (nums[low] > nums[mid])
{
high = mid;
}
// right half
else
{
low = mid + 1;
}
}
return nums[low];
}
bool Solution::test(vector<int> &nums, int answer)
{
return findMin(nums) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int findMin(vector<int> &nums);
bool test(vector<int> &nums, int answer);
};