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
}
相关推荐
stand_forever2 小时前
PHP客户端调用由Go服务端GRPC接口
rpc·golang·php
flashlight_hi4 小时前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表
Tisfy4 小时前
LeetCode 2536.子矩阵元素加 1:二维差分数组
算法·leetcode·矩阵
席万里4 小时前
通过Golang订阅binlog实现轻量级的增量日志解析,并解决缓存不一致的开源库cacheflow
缓存·golang·开源
q***46525 小时前
对基因列表中批量的基因进行GO和KEGG注释
开发语言·数据库·golang
柠石榴5 小时前
GO-1 模型本地部署完整教程
开发语言·后端·golang
大Null5 小时前
Linux安装GO环境
linux·golang
小欣加油5 小时前
leetcode 2536 子矩阵元素加1
数据结构·c++·算法·leetcode·矩阵
努力学算法的蒟蒻6 小时前
day14(11.14)——leetcode面试经典150
算法·leetcode
海琴烟Sunshine10 小时前
leetcode 383. 赎金信 python
python·算法·leetcode