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.
eg:

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的向量,然后每次给其中的(n-1)个元素加1,最终向量的状态是每个元素都相同,问最少需要重复这样的操作多少次才能到达最终状态。

自己刚开始的思路是假设最终向量中的每个元素值都为m,之前向量中的最大元素为big,元素和为sum,那么,最终移动的次数为(m * big - sum)/(n - 1),这个式子应该很好理解。但是提交之后,发现对于某些测试出现溢出现象(溢出出现在讲原向量中的所有元素加和),后来,我想到改数据类型到long long,可是这种方式始终是治标不治本的。
这种方式的代码:

class Solution {
public:
    int minMoves(vector<int>& nums) {
        int big = *max_element(nums.begin(), nums.end());
        long long int m, n = nums.size();
        long long int sum = accumulate(nums.begin(), nums.end(), 0);
        if(n == 1)
          return 0;

        for(m = big; ;m++){
            int a = (m * n - sum) % (n - 1);
            if(a == 0)
              break;
        }
        return (m * n - sum) / (n - 1);
    }
};

后来想到,如果最小的移动方式是将向量中除了最大元素的其他元素每次都加1,直至向量中的元素都相同,那么不就相当于将向量中的最大元素每次减1,直至向量中的所有元素都和之前向量中的最小值相同吗,思路有了,代码就很好写了:

class Solution {
public:
    int minMoves(vector<int>& nums) {
        int bot = *min_element(nums.begin(), nums.end());
        int n = nums.size();

        if(n == 1)
          return 0;

        int count = 0;
        for(int i = 0; i < n; i ++){
          count += nums[i] - bot;
        }
        return count;

    }
};

这道题中,题目明确定义了向量中元素类型是int型,但是应该考虑到,如果叠加向量中的元素,很有可能会越界;而且,这道题,可以从反面思考,使用减法,这样就不会越界。
对于C++,我是菜鸟,代码里面用到的*min_element以及accumulate函数之前没有接触到,一会儿把它们添加到有关C++ STL的博客里。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值