And there is another perspective, instead of iterating numbers, we can iterate distances. Like:
const closest_num = (nums, given_num) => { const set = new Set(nums) let i = 0 while (true) { if (set.has(given_num - i)) return given_num - i if (set.has(given_num + i)) return given_num + i i++ } }
This will normally be slower, but in cases like:
nums = [10000000, 9999999, 9999998, ..., 1] given_num = 10000001
nums = [10000000, 9999999, 9999998, ..., 1]
given_num = 10000001
It will be much faster than other algorithms.
I have written a benchmark function for this:
const benchmark = (func) => { console.time(func.name) func.call(this, Array.from({length: 10000000}, (v, idx) => (10000000 - idx)), 10000001) console.timeEnd(func.name) }
You can test your function via benchmark(func).
benchmark(func)
The solution above yields:
closest_num: 5037.456787109375ms
in Chrome.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
And there is another perspective, instead of iterating numbers, we can iterate distances. Like:
This will normally be slower, but in cases like:
nums = [10000000, 9999999, 9999998, ..., 1]
given_num = 10000001
It will be much faster than other algorithms.
I have written a benchmark function for this:
You can test your function via
benchmark(func)
.The solution above yields:
closest_num: 5037.456787109375ms
in Chrome.