https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/
Find the median instead of the mean.
int minMoves2(vector<int>& nums) {
int N = nums.size();
if(N<2) return 0;
auto it = nums.begin() + N/2;
// nth_element is a partial sorting algorithm
nth_element(nums.begin(), it, nums.end());
int median = *it;
int res = 0;
for(int n : nums) res += abs(n - median);
return res;
}
No comments:
Post a Comment