Skip to content

Create 19 May Find the closest number #376

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions 19 May Find the closest number
Original file line number Diff line number Diff line change
@@ -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];
}
};