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
}
相关推荐
chao_7892 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表
海奥华24 小时前
go中的接口返回设计思想
开发语言·后端·golang
岁忧5 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 上
sql·算法·leetcode
eachin_z5 小时前
力扣刷题(第四十九天)
算法·leetcode·职场和发展
飞川撸码8 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
_Itachi__16 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
roman_日积跬步-终至千里16 小时前
【Go语言基础【14】】defer与异常处理(panic、recover)
golang
孔令飞17 小时前
Kubernetes 节点自动伸缩(Cluster Autoscaler)原理与实践
ai·云原生·容器·golang·kubernetes
chao_78917 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表