Minimum Moves to Equal Array Elements

本文探讨了一个整数数组问题,目标是找到使数组元素相等所需的最少移动次数,移动包括增加或减少选定元素的值。文章提供了一种高效的解决方案,通过找到数组的中位数并计算所有元素与中位数的距离之和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 问题描述
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.

2简要分析
该题目可以按照数学中函数单调性那样思考。给定一个数k作为数组的数需要靠近的目标,假设原数列中有m个小于等于K的数,有n个大于k的数。
(1)如果m

int minMoves3(vector<int>& nums) {
        int n = nums.size();
        auto it = nums.begin() + n / 2;
        nth_element(nums.begin(), it, nums.end());
        int median = *it;
        int total = 0;
        for (auto &i : nums)
            total += abs(i - median);
        return total;
    }

4 总结
最开始思考这问题的时候用动态规划来解,程序也能做出来,但是复杂度比这个算法高,代码量大,之后看别人求解时发现这种方法更优雅,更高效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值