From 5f1e2efa9e9cc8b9b162ad4ab40604c97d85d917 Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Sun, 19 Nov 2023 14:43:04 -0700 Subject: [PATCH] day 40: 153-find-minimum-in-rotated-sorted-array --- .../driver.cpp | 10 ++++++ .../soln.cpp | 31 +++++++++++++++++++ .../soln.hpp | 8 +++++ 3 files changed, 49 insertions(+) create mode 100644 153-find-minimum-in-rotated-sorted-array/driver.cpp create mode 100644 153-find-minimum-in-rotated-sorted-array/soln.cpp create mode 100644 153-find-minimum-in-rotated-sorted-array/soln.hpp 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