Golang | Leetcode Golang题解之第462题最小操作次数使数组元素相等II

题目:

题解:

Go 复制代码
func partition(a []int, l, r int) int {
    x := a[r]
    i := l - 1
    for j := l; j < r; j++ {
        if a[j] <= x {
            i++
            a[i], a[j] = a[j], a[i]
        }
    }
    a[i+1], a[r] = a[r], a[i+1]
    return i + 1
}

func randomPartition(a []int, l, r int) int {
    i := rand.Intn(r-l+1) + l
    a[i], a[r] = a[r], a[i]
    return partition(a, l, r)
}

func quickSelect(a []int, l, r, index int) int {
    q := randomPartition(a, l, r)
    if q == index {
        return a[q]
    }
    if q < index {
        return quickSelect(a, q+1, r, index)
    }
    return quickSelect(a, l, q-1, index)
}

func minMoves2(nums []int) (ans int) {
    rand.Seed(time.Now().UnixNano())
    x := quickSelect(nums, 0, len(nums)-1, len(nums)/2)
    for _, num := range nums {
        ans += abs(num - x)
    }
    return
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}
相关推荐
sunflower#5 小时前
Go学习第五阶段:接口、泛型与包设计,实现可替换的通讯录存储层
学习·oracle·golang
不会就选b5 小时前
算法日常・每日刷题--<贪心>7
数据结构·算法·leetcode
ShuiShenHuoLe10 小时前
golang-jwt v5 入门
开发语言·后端·golang
smj2302_7968265212 小时前
解决leetcode第4017题数组中的峰值II
python·算法·leetcode
午彦琳12 小时前
2026.9.9
数据结构·算法·leetcode
橘子汽水16813 小时前
Leetcode 200,994岛屿数量,腐烂的橘子
数据结构·算法·leetcode
geovindu13 小时前
go: Task Scheduler
开发语言·后端·golang
Tisfy15 小时前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
find1star15 小时前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
吞下星星的少年·-·16 小时前
LeetCode 热题 100 两数之和(哈希表)
算法·leetcode·哈希算法