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.
func minMoves(nums []int) int {
sort.Ints(nums)
if len(nums) == 1 {
return 0
}
preM, preN := 0, nums[0]
for i := 1; i < len(nums); i++ {
curN := nums[i] + preM
preM = preM + curN - preN
preN = curN
}
return preM
}
本文介绍了一种算法,如何通过最少的操作次数,使得整数数组的所有元素相等。通过排序并利用移动策略,找到最优的增量方案。主要讨论了如何在`nums[]`数组中使用一次移动操作增加n-1个元素的方法来简化问题。
475

被折叠的 条评论
为什么被折叠?



