[LeetCode 453] Minimum Moves to Equal Array Elements

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

题目本身意思是说,定义了一个批操作,可以一次把长度为n的数组内的n-1个元素批量自增一,问需要多少次操作能让所有元素相等?

一次关注多个元素的变化比较复杂,这个例子给的提示也不明显。我们可以换个视角来看:一次操作只是把某个元素减一,其他元素不变。

这样思路就清晰了很多,我们只需要看需要多少步能把所有元素都拉低到最小元素的水平就可以了。比如 [1,1,3]这个例子,把3降到1只需要两步就可以。

所以解答代码如下:

// @lc code=start
class Solution {
public:
    // [1,2,3] -> 3
    // [1,1,3] -> 2
    int minMoves(vector<int>& nums) {
        int res = 0;
        int val = nums[0];
        for (int x : nums) {
            val = min(val, x);
        }
        for (int x : nums) {
            res += x - val;
        }
        return res;
    }
};
// @lc code=end
原文地址:https://www.cnblogs.com/zhcpku/p/14253847.html