We're a place where coders share, stay up-to-date and grow their careers.
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; }
C++, O(n), no sorting, no extra memory allocation beyond storing the input: