diff --git a/153-find-minimum-in-rotated-sorted-array/driver.cpp b/153-find-minimum-in-rotated-sorted-array/driver.cpp new file mode 100644 index 0000000..6ea959c --- /dev/null +++ b/153-find-minimum-in-rotated-sorted-array/driver.cpp @@ -0,0 +1,10 @@ +#include "soln.hpp" + +int main() +{ + vector 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; +} \ No newline at end of file diff --git a/153-find-minimum-in-rotated-sorted-array/soln.cpp b/153-find-minimum-in-rotated-sorted-array/soln.cpp new file mode 100644 index 0000000..9e765f6 --- /dev/null +++ b/153-find-minimum-in-rotated-sorted-array/soln.cpp @@ -0,0 +1,31 @@ +#include "soln.hpp" + +int Solution::findMin(vector &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 &nums, int answer) +{ + return findMin(nums) == answer; +} diff --git a/153-find-minimum-in-rotated-sorted-array/soln.hpp b/153-find-minimum-in-rotated-sorted-array/soln.hpp new file mode 100644 index 0000000..1f3755e --- /dev/null +++ b/153-find-minimum-in-rotated-sorted-array/soln.hpp @@ -0,0 +1,8 @@ +#include +using namespace std; +class Solution +{ +public: + int findMin(vector &nums); + bool test(vector &nums, int answer); +}; \ No newline at end of file