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]
【问题分析】

 举几个例子,可以发现规律,每次做move操作,只需要对除最大数以外的数加1,最终会达到所有数相等

 例如:[1,2,3]

 第一步:对第1、2个数分别加1,得到2,3,3

 第二步:对第1、2个数分别加1,得到3,4,3

 第三步:对第1、3个数分别加1,得到4,4,4

 其实上述步骤等价于:

 第一步:对第3个数减1,得到1,2,2

 第二步:对第3个数减1,得到1,2,1

 第三步:对第2个数减1,得到1,1,1

 即每次对最大数减去1,最终能达到所有数相等(从这里往下的计算是关键)

 利用等价方法,因为最终所有数字都等于最小的那个数,对任意第i个位置上的数字,需要经历num[i]-min步数才能和最小数相等,

 而且每个数字是当前最大数的时候才会被减1,因此,全部步数就等于,所有数字经历的步数和

 即:全部步数等于每个数和最小数字的差值之和

【AC代码】

 

class Solution {
public:
    int minMoves(vector<int>& nums) {
            int count = 0;
            if (nums.empty()) {
                return 0;
            }
            int min = nums[0];
            for (int i = 0; i < nums.size(); ++i) {
                if (nums[i] < min) {
                    min = nums[i];
                }
            }

            for (int i = 0; i < nums.size(); ++i) {
                count += nums[i] - min;
            }

            return count;       
    }
};

参考内容:

https://discuss.leetcode.com/topic/66788/c-_accepted_o-nlogn-o-n

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值