From 9fa13e7447fec6e9d4a41d5697fd491871a7b210 Mon Sep 17 00:00:00 2001 From: Manish Date: Sun, 12 Mar 2023 12:07:19 +1100 Subject: [PATCH] Design Pattern 12: Modified Binary Search | Problem: Bitonic Point --- 12_bitonic_point.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++ CMakeLists.txt | 4 +++- 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 12_bitonic_point.cpp diff --git a/12_bitonic_point.cpp b/12_bitonic_point.cpp new file mode 100644 index 0000000..929ecab --- /dev/null +++ b/12_bitonic_point.cpp @@ -0,0 +1,55 @@ +/* Problem: + * https://practice.geeksforgeeks.org/problems/maximum-value-in-a-bitonic-array3001/1 + */ + +#include +#include + +int solution(const std::vector &nums) { + if (nums.size() == 0) { + return -1; + } + if (nums.size() == 1) { + return 0; + }; + long long first = 0, last = nums.size() - 1, pi = last / 2; + while (true) { + if (pi == 0) { + if (nums[pi] > nums[pi + 1]) { + return pi; + } else { + first = pi + 1; + pi = ((last - first) / 2) + first; + continue; + } + } else if (pi == (long long)nums.size() - 1) { + if (nums[pi] > nums[pi - 1]) { + return pi; + } else { + last = pi - 1; + pi = ((last - first) / 2) + first; + continue; + } + } + if (nums[pi] < nums[pi - 1]) { + last = pi - 1; + } else if (nums[pi] < nums[pi + 1]) { + first = pi + 1; + } else { + return pi; + } + pi = ((last - first) / 2) + first; + } + + return pi; +} + +int main() { + std::vector nums1 = {1, 15, 25, 45, 42, 21, 17, 12, 11}, + nums2 = {1, 45, 47, 50, 5}; + int i1, i2; + i1 = solution(nums1); + std::cout << i1 << " : " << nums1[i1] << '\n'; + i2 = solution(nums2); + std::cout << i2 << " : " << nums2[i2] << '\n'; +} \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index eaa1c32..a21cad2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,4 +27,6 @@ add_executable(10_find_the_median_of_a_number_stream 10_find_the_median_of_a_num add_executable(11_letter_case_permutation 11_letter_case_permutation.cpp) -add_executable(11_permutations_in_string 11_permutations_in_string.cpp) \ No newline at end of file +add_executable(11_permutations_in_string 11_permutations_in_string.cpp) + +add_executable(12_bitonic_point 12_bitonic_point.cpp)