zoukankan      html  css  js  c++  java
  • Leetcode453.Minimum Moves to Equal Array Elements最小移动次数使数组元素相等

    给定一个长度为 n 的非空整数数组,找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。

    示例:

    输入: [1,2,3] 输出: 3 解释: 只需要3次移动(注意每次移动会增加两个元素的值): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]

    每次给除去最大值的其余数字加1,但这种方法效率过低,可以换一种思路。每次将数组中的n-1个数字加1,相当于将剩余的一个数字减1。所以只需找到数组中的最小值m,计算m与数组中其他数字差的累计和即可。

    bool cmd(int x, int y)
    {
        return x < y;
    }
    
    class Solution {
    public:
        int minMoves(vector<int>& nums) {
            int len = nums.size();
            int res = 0;
            sort(nums.begin(), nums.end());
            for(int i = 1; i < len; i++)
            {
                res += nums[i] - nums[0];
            }
            return res;
        }
    };
  • 相关阅读:
    source命令
    [电脑配置]屏幕扩展过,找不到界面
    [SAS]方便查询Tips
    [Excel]方便查询Tips
    [SAS]运用函数等的一些问题
    [SAS]错误整理
    [SAS]易错例子之数值型转字符型
    [R]Precedence
    [sas]Missing Value
    [SAS]
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10434080.html
Copyright © 2011-2022 走看看