Minimum Moves to Equal Array Elements II

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array's length is at most 10,000.

Example:

Input:
[1,2,3]

Output:
2

Explanation:
Only two moves are needed (remember each move increments or decrements one element):

[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

这道题跟1的思路有点像,要寻找最后所有数字都是一样的那个数字N。 为了移动的次数最小,显然应该是中位数。刚刚纠结了下如果是奇数该怎么办。但是又一想,无论是以左边还是右边为基础, 移动的次数一定是相同的。感觉需要回小学再补习一下数学。。

那么有这个规律了,代码实现就很简单了。


代码:

public int minMoves2(int[] nums) {
        //与中位数的差的绝对值的和
        if(nums == null || nums.length ==0) return 0;
        
        Arrays.sort(nums);
        int median = nums[nums.length/2];
        int sum = 0;
        for(int i=0;i


你可能感兴趣的:(算法,leetcode)