Minimum Moves to Equal Array Elements II

2017/12/11 posted in  leetcode

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int n = nums.size();
        if(n <= 1) return 0;
        sort(nums.begin(), nums.end());
        int mid = nums.size()/2 ,res = 0;
        for(int i = 0; i < mid; ++i)
        {
            res+=nums[mid]-nums[i];
        }
        for (int j = n-1; j>mid; j--) {
            res+=nums[j]-nums[mid];
        }
        return res;
    }
};