From fa5fcba01dac59a2e0bd8fda5161d9ee8bc93c4c Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Sun, 19 May 2024 22:23:35 +0530 Subject: [PATCH] Create 19 May Find the closest number --- 19 May Find the closest number | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 19 May Find the closest number diff --git a/19 May Find the closest number b/19 May Find the closest number new file mode 100644 index 00000000..80aa86af --- /dev/null +++ b/19 May Find the closest number @@ -0,0 +1,20 @@ +class Solution { +public: + int findClosest(int n, int k, int arr[]) { + // Using lower_bound to find the position where 'k' would be inserted + int lb = lower_bound(arr, arr + n, k) - arr; + + // If the element at the lower bound is exactly 'k', return 'k' + if (arr[lb] == k) return k; + + // If the lower bound index is greater than 0, we need to compare with the previous element + if (lb > 0) { + // Compare the differences to find the closest element + if (k - arr[lb - 1] < arr[lb] - k) return arr[lb - 1]; + else return arr[lb]; + } + + // If the lower bound index is 0, the only option is the first element + return arr[lb]; + } +};