LeetCode - 453/462 - 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,问操作多少次可以使所有的数相等。时间复杂度O(n)

数学题0.0设数组中所有数的和为sum,n为数组的长度,操作了m次,最后所有数都变成x,则有

sum + m * (n - 1) = x * n

x = mmin + m

m = sum - mmin * n

class Solution {
public:
    int minMoves(vector<int>& nums) {
        int n = nums.size();
        if (n <= 1) return 0;
        int sum = 0;
        int mmin = nums[0];
        for (auto x: nums) {
            sum += x;
            mmin = min(mmin, x);
        }
        return sum - mmin * n;
    }
};



462. Minimum Moves to Equal Array Elements II

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array's length is at most 10,000.

Example:

Input:
[1,2,3]

Output:
2

Explanation:
Only two moves are needed (remember each move increments or decrements one element):

[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

每次操作可以把一个数+1或者-1,问多少次操作可以使数组中数都相等。

选择一个中位数,然后让所有的数都等于这个数即可。排序之后,从两边往中间走,大值和小值之间的差距,是一定要填补上的,不管+1 还是 -1,所以最后都等于中位数。

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int n = nums.size();
        if (n <= 1) return 0;
        sort(nums.begin(), nums.end());
        int sum = 0;
        int i = 0, j = n - 1;
        while (i < j) {
            sum += nums[j]- nums[i];
            i++;
            j--;
        }
        return sum;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值