453. Minimum Moves to Equal Array Elements

来源:互联网 发布:淘宝客有没有权重 编辑:程序博客网 时间:2024/05/17 23:02

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:3Explanation: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
原创粉丝点击