首页 > 其他 > 详细

453. Minimum Moves to Equal Array Elements

时间:2020-07-03 12:38:35      阅读:56      评论:0      收藏:0      [点我收藏+]

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.

技术分享图片

 

453. Minimum Moves to Equal Array Elements

原文:https://www.cnblogs.com/wentiliangkaihua/p/13229282.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!