453. Minimum Moves to Equal Array Elements

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

Example:

Input:
[1,2,3]

Output:
3

Explanation:
Only three moves are needed (remember each move increments two elements):

[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]
public class Solution {
    public int minMoves(int[] nums) {
        if (nums.length == 0) return 0;
        int min = nums[0];
        for (int n : nums) min = Math.min(min, n);
        int res = 0;
        for (int n : nums) res += n - min;
        return res;
    }
}

我日,这些人脑子里都在想什么?这答案也太brainteaser了

意思是:要给n-1位进行++,那我说我偏不,我就给所有n个数--,然后再给n-1个数++也可以吧?因为我们知道整体挪动不影响大局

那么问题来了,这是什么呢?这就是给1个数进行--,

然后问题就变成:只能一次对一个数进行--运算,要多少次才能让所有数相等。

最后就变成:找到minimum,让所有其他数向他靠拢

卧槽!

https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93815/Java-O(n)-solution.-Short.

 

posted @ 2020-07-03 11:15  Schwifty  阅读(127)  评论(0编辑  收藏  举报