Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement an element of the array by 1.
Test cases are designed so that the answer will fit in a 32-bit integer.
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intminMoves2(vector<int>& A){ sort(begin(A), end(A)); int n = A.size(), m = A[n/2]; int res = 0; for(auto& a : A) res += abs(m-a); return res; } };
classSolution { longlonghelper(vector<int>& A, int k){ longlong res = 0; for(auto& a : A) { res += abs(k - a); } return res; } public: intminMoves2(vector<int>& A){ longlong res = LLONG_MAX, ma = *max_element(begin(A), end(A)), mi = *min_element(begin(A), end(A)); while(mi <= ma) { int m = mi + (ma - mi) / 2; longlong diff = helper(A, m); longlong diff2 = helper(A, m + 1); if(diff < diff2) ma = m - 1; else mi = m + 1; res = min({res, diff, diff2}); } return res; } };