re: Challenge: Get Closest Number in an Array VIEW POST

FULL DISCUSSION
 

C++, O(n), no sorting, no extra memory allocation beyond storing the input:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v{100, 200, 400, 800, 1600, 3200, 6400, 128000};
    int given_num = 900;

    cout << *min_element(
        v.begin(), 
        v.end(), 
        [=](int a, int b){ return abs(a - given_num) < abs(b - given_num); }
    );

    return 0;
}
code of conduct - report abuse