Python 中使数组元素相等的最少移动次数 II
pythonserver side programmingprogramming更新于 2025/10/31 15:08:17
假设我们有一个非空整数数组,我们必须找到使所有数组元素相等所需的最少移动次数,其中移动是将选定元素增加或减少 1。因此,当数组为 [1, 2, 3] 时,输出将为 2,因为 1 将增加到 2,而 3 将减少到 2。
为了解决这个问题,我们将遵循以下步骤 −
- 对数组 nums 进行排序
- 将 counter 设置为 0
- 对于 nums 中的 i,执行
- counter := counter + absolute of (i – nums[length of nums / 2])
- 返回 counter
示例 (Python)
让我们看下面的实现,以便更好地理解 −
class Solution: def minMoves2(self, nums): nums.sort() counter = 0 for i in nums: counter += abs(i-nums[len(nums)//2]) return counter ob1 = Solution() print(ob1.minMoves2([2,5,3,4]))
输入
[2,5,3,4]
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

