[LeetCode] Minimum Moves to Equal Array Elements

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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-1个数都加1,最后使所有数字都相等,计算加1的次数。本质上这是一个数字问题,令数组中元素和为sum,数组的长度为n,最小的元素值为min,达到平衡时的数字为x,加1的次数为m,则sum + m * (n - 1) = x * n。实际上x = min + m,所以m = sum - min * n。
class Solution {
public:
    int minMoves(vector<int>& nums) {
        int n = nums.size();
        int sum = 0;
        sort(nums.begin(), nums.end());
        for (int num : nums)
            sum += num;
        return sum - nums[0] * n;
    }
};
// 82 ms

 如果要使所有的数字都相等,则每个值到最大值之间的差都应该被计算为执行的次数。

class Solution {
public:
    int minMoves(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int res = 0;
        for (int i = 0; i != nums.size(); i++)
            res += (nums[i] - nums[0]);
        return res;
    }
};
// 76 ms

 

以上是关于[LeetCode] Minimum Moves to Equal Array Elements的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 453. Minimum Moves to Equal Array Elements

[LeetCode] Minimum Moves to Equal Array Elements

Leetcode: Minimum Moves to Equal Array Elements II

[LeetCode] Minimum Moves to Equal Array Elements II

LeetCode 453 Minimum Moves to Equal Array Elements

453. Minimum Moves to Equal Array Elements(LeetCode)