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
}
相关推荐
Espresso Macchiato31 分钟前
Leetcode 3748. Count Stable Subarrays
算法·leetcode·职场和发展·leetcode hard·leetcode 3748·leetcode周赛476·区间求和
脉动数据行情4 小时前
Go语言对接股票、黄金、外汇API实时数据教程
开发语言·后端·golang
天选之女wow4 小时前
【Hard——Day4】25.K 个一组翻转链表
数据结构·算法·leetcode·链表
Dream it possible!10 小时前
LeetCode 面试经典 150_二叉树_二叉树中的最大路径和(77_124_C++_困难)(DFS)
c++·leetcode·面试·二叉树
做怪小疯子14 小时前
LeetCode 热题 100——子串——和为 K 的子数组
算法·leetcode·职场和发展
希望有朝一日能如愿以偿19 小时前
力扣每日一题:仅含1的子串数
算法·leetcode·职场和发展
q***710820 小时前
【Golang】——Gin 框架中的表单处理与数据绑定
microsoft·golang·gin
苏小瀚20 小时前
算法---FloodFill算法和记忆化搜索算法
数据结构·算法·leetcode
少许极端1 天前
算法奇妙屋(十二)-优先级队列(堆)
数据结构·算法·leetcode·优先级队列··图解算法