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
}
相关推荐
Morwit42 分钟前
*【力扣hot100】 647. 回文子串
c++·算法·leetcode
iso少年1 小时前
Go 语言并发编程核心与用法
开发语言·后端·golang
菜鸟233号2 小时前
力扣96 不同的二叉搜索树 java实现
java·数据结构·算法·leetcode
千金裘换酒2 小时前
Leetcode 有效括号 栈
算法·leetcode·职场和发展
空空潍2 小时前
hot100-最小覆盖字串(day12)
数据结构·算法·leetcode
POLITE36 小时前
Leetcode 142.环形链表 II JavaScript (Day 10)
javascript·leetcode·链表
王老师青少年编程6 小时前
2025年12月GESP(C++)考级真题及详细题解(汇总版)
c++·题解·真题·gesp·csp·信奥赛·考级
千金裘换酒7 小时前
Leetcode 二叉树中序遍历 前序遍历 后序遍历(递归)
算法·leetcode·职场和发展
风送雨7 小时前
Go 语言进阶学习:第 2 周 —— 接口、反射与错误处理进阶
开发语言·学习·golang
Tisfy7 小时前
LeetCode 1339.分裂二叉树的最大乘积:深度优先搜索(一次DFS+存数组并遍历)
算法·leetcode·深度优先·题解