首页 > 其他 > 详细

[LeetCode 453] Minimum Moves to Equal Array Elements

时间:2021-01-09 00:36:23      阅读:26      评论:0      收藏:0      [点我收藏+]

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

[LeetCode 453] Minimum Moves to Equal Array Elements

原文:https://www.cnblogs.com/zhcpku/p/14253847.html

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