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
}
相关推荐
玖玥拾37 分钟前
LeetCode 205 同构字符串
算法·leetcode
小翰生信2 小时前
转录组下游分析全流程:DESeq2 差异分析、GO/KEGG 富集与 GSEA 实战
数据库·矩阵·golang
_不会dp不改名_3 小时前
leetcode3875_构造奇偶一致的数组 I
leetcode
圣保罗的大教堂11 小时前
leetcode 1406. 石子游戏 III 困难
leetcode
Data_Journal19 小时前
Scrapyd:分步教程
开发语言·python·microsoft·golang·编辑器·html·iphone
带多刺的玫瑰19 小时前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展
圣保罗的大教堂19 小时前
leetcode 877. 石子游戏 中等
leetcode
shehuiyuelaiyuehao21 小时前
算法32,连续数组,前缀和+哈希表
算法·leetcode·职场和发展
程序员小八7771 天前
Go Web 工程化:日志、配置与错误处理中间件,让服务「能上线」
前端·中间件·golang
Navigator_Z1 天前
LeetCode //C - 1223. Dice Roll Simulation
c语言·算法·leetcode