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.

&nbsp;
Example 1:

Input: nums = [1,2,3]
Output: 2
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3]  =&gt;  [2,2,3]  =&gt;  [2,2,2]


Example 2:

Input: nums = [1,10,2,9]
Output: 16


&nbsp;
Constraints:


	n == nums.length
	1 &lt;= nums.length &lt;= 105
	-109 &lt;= nums[i] &lt;= 109


class Solution:
    def minMoves2(self, nums: List[int]) -> int:
        
        n=len(nums)
        nums.sort()
        
        if n%2==1:
            median=nums[n//2]
        else:
            median = (nums[n//2 - 1] + nums[n//2]) // 2
        
        ans=0
        
        for val in nums:
            ans+=abs(val-median)
        
        return ans
        
class Solution {
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int idx=(nums.length-1)/2;
        int sum=0;
        for(int i=0;i<nums.length;i++){
            sum+=Math.abs(nums[i]-nums[idx]);
        }
        return sum;
    }
}
class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int result = 0, length = nums.size();
        sort(nums.begin(), nums.end());
        for (int i = 0; i < length; i++) {
            int median = length / 2;
            result += abs(nums[i] - nums[median]);
        }
        return result;
    }
};
var minMoves2 = function(nums) {
    // Sort the array low to high
    nums.sort(function(a, b) { return a-b;});
    let i = 0;
    let j = nums.length - 1;
    let res = 0;
    /**
     * Sum up the difference between the next highest and lowest numbers. Regardless of what number we wish to move towards, the number of moves is the same.
     */
    while (i < j){
        res += nums[j] - nums[i];
        i++;
        j--;
    }
    return res;
};
Minimum Moves to Equal Array Elements II