You are viewing a single comment's thread. Return to all comments →
c++ . Using only one loop after sort:
vector<int> closestNumbers(vector<int> arr) { sort(arr.begin(), arr.end()); int diffMin = INT32_MAX; vector<int> r; for (int i = 0, e = arr.size() - 1; i < e; ++i) { const int diffCurrent = arr[i + 1] - arr[i]; if (diffCurrent < diffMin) { diffMin = diffCurrent; r.clear(); } if (diffCurrent == diffMin) { r.push_back(arr[i]); r.push_back(arr[i + 1]); } } return r; }
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Numbers
You are viewing a single comment's thread. Return to all comments →
c++ . Using only one loop after sort: