C++ O(n) using STL

  • 0
    class Solution {
        int minMoves2(vector<int>& nums) {
            if (nums.empty()) return 0;
            nth_element(nums.begin(), nums.begin() + nums.size()/2, nums.end());
            int median = nums[nums.size()/2];
            int count = 0;
            for (auto &n: nums) count += abs(n - median);
            return count;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.