xinyu04

导航

[Oracle] LeetCode 453 Minimum Moves to Equal Array Elements

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment n - 1 elements of the array by 1.

Solution

实际上样例具有欺骗性。刚开始思路比较难想。先将序列排序,我们想要所有的数字变成同一个数,从贪心的角度出发,我们使相邻的较小元素变成较大的那个。也就是保持较大的那个不变,将剩下的 \(n-1\) 统一加上二者之差。接着对于下一个相邻元素也是相同的做法。所以这时你可以发现本质就是最小值与每一个的差。

点击查看代码
class Solution {
private:
    int ans=0;
    
public:
    int minMoves(vector<int>& nums) {
        int n = num.size();
        sort(nums.begin(), nums.end());
        for(int i=0;i<n;i++){
            ans+= (nums[i]-nums[0]);
        }
        return ans;
    }
};

posted on 2022-08-24 15:45  Blackzxy  阅读(11)  评论(0编辑  收藏  举报