zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    hero
    今年暑假不AC
    Who's in the Middle
    A Simple Problem with Integers
    I hate it
    敌兵布阵
    Ordering Tasks
    Points on Cycle
    食物链
    c++ 14.0下载地址
  • 原文地址:https://www.cnblogs.com/immjc/p/7163247.html
Copyright © 2011-2022 走看看