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
}
相关推荐
愚润求学1 小时前
【专题刷题】二分查找(一):深度解刨二分思想和二分模板
开发语言·c++·笔记·leetcode·刷题
岩中竹1 小时前
力扣热题100题解(c++)—矩阵
数据结构·c++·程序人生·算法·leetcode·矩阵
草海桐2 小时前
go 的 net 包
网络·golang·net
刃神太酷啦3 小时前
堆和二叉树--数据结构初阶(3)(C/C++)
c语言·数据结构·c++·算法·leetcode·深度优先·宽度优先
●VON4 小时前
杭电oj(1087、1203、1003)题解
算法·leetcode·职场和发展
良木林4 小时前
240424 leetcode exercises II
c语言·数据结构·算法·leetcode
WaitWaitWait0112 小时前
LeetCode每日一题4.20
算法·leetcode
蒟蒻小袁12 小时前
力扣面试150题--有效的括号和简化路径
算法·leetcode·面试
Xiaoyu Wang14 小时前
Go协程的调用与原理
开发语言·后端·golang
阳洞洞15 小时前
leetcode 二分查找应用
算法·leetcode·二分查找