5-Line C++ O(n) Solution using Quick-select (beat 82%)


  • 1
    W

    The target value that all elements should reach is the median~

    int minMoves2(vector<int>& nums) {
            auto mid = nums.begin() + nums.size()/2;
            nth_element(nums.begin(), mid, nums.end());
            int median = *mid, count = 0;
            for(int e: nums) count += abs(e-median);
            return count;
    }
    

Log in to reply
 

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