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
}
相关推荐
blxr_5 小时前
力扣hot100爬楼梯https://leetcode.cn/problems/climbing-stairs/
算法·leetcode·职场和发展
EatFan6 小时前
Go语言全栈实战:基于 Gin + Vue + JWT + RBAC 从零搭建前后端分离权限管理系统
vue.js·golang·go·vue·gin·jwt·rbac
ZealSinger7 小时前
Go slog生产落地LevelVar与共存
开发语言·后端·golang·go
Navigator_Z7 小时前
LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
c语言·算法·leetcode
丹宇码农7 小时前
Go 与 Python 协程(Coroutine)对比演示项目
开发语言·python·golang
ttwuai7 小时前
Go开源后台管理系统推荐:3个官方仓库怎么按技术栈和适用边界比较?
开发语言·golang·开源
All for pursuit.9 小时前
【分治-2】215.数组中的第K个最大元素
数据结构·c++·算法·leetcode
茉莉玫瑰花茶9 小时前
GO [ 并发 · 调度器 ]
开发语言·后端·golang
恋喵大鲤鱼9 小时前
go list command
golang·list
blxr_10 小时前
力扣hot100前k个高频元素https://leetcode.cn/problems/top-k-frequent-elements/
算法·leetcode·职场和发展