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
}
相关推荐
Musennn3 小时前
leetcode 15.三数之和 思路分析
算法·leetcode·职场和发展
IsPrisoner8 小时前
Go语言安装proto并且使用gRPC服务(2025最新WINDOWS系统)
开发语言·后端·golang
littleschemer8 小时前
Go基于plugin的热更新初体验
golang·plugin·热更新
MarkHard1239 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
言之。9 小时前
Go语言中的函数类型参数:深入理解`func()`
golang
我重来不说话12 小时前
免费Ollama大模型集成系统——Golang
golang·gin·ollama·免费大模型
Asus.Blogs12 小时前
为什么go语言中返回的指针类型,不需要用*取值(解引用),就可以直接赋值呢?
开发语言·后端·golang
小羊在奋斗13 小时前
【LeetCode 热题 100】反转链表 / 回文链表 / 有序链表转换二叉搜索树 / LRU 缓存
算法·leetcode·链表
爱上彩虹c13 小时前
LeetCode Hot100 (1/100)
算法·leetcode·职场和发展