LeetCode 462. 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]

【思路分析】

这个题目和Minimum Moves to Equal Array Elements类似。在前面这个题目中我们变换一种求解问题的思路,把在n-1个数上加1的操作转换为在每个数上进行减一操作,直到每个数都减到最小值。在这个题目中我们的每一步操作是对数组中的一个数加1或者减1,直到所有的数相同。一个想法就是上大的数减小,小的数增加,直到他们都等于中间值。

1. 首先对数组进行排序

2. 找到中间值mid

3. 遍历数组,求nums[i]-mid的和

由于不保证数组元素个数为奇数个,因此不一定存在中间值。通用解法如下:

1. 首先对数组进行排序

2. 首尾数字两两配对,求出它们差值的和。

代码如下:

 1 public class Solution {
 2     public int minMoves2(int[] nums) {
 3         Arrays.sort(nums);
 4         int i = 0, j = nums.length - 1;
 5         int count = 0;
 6         while(i < j) {
 7             count += nums[j--] - nums[i++];
 8         }
 9         
10         return count;
11     }
12 }
原文地址:https://www.cnblogs.com/liujinhong/p/6208770.html