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
}
相关推荐
吞下星星的少年·-·9 小时前
LeetCode 热题 100 最长连续序列(哈希表)
算法·leetcode·散列表
Pniubi10 小时前
力扣25.K个一组反转链表
算法·leetcode·链表
sunly_11 小时前
Go 切片详解
开发语言·oracle·golang
小白的高手之路11 小时前
【LeetCode 热题 100】560. 和为 K 的子数组|前缀和、哈希表(Python)
数据结构·笔记·python·算法·leetcode·力扣·散列表
利威尔xu14 小时前
Go interface 底层:空接口装任何东西,类型断言漏写 ok 直接 panic 拖垮服务
开发语言·golang·interface·类型断言·itab
Zenova EdgeOS14 小时前
Go Redis 实战:工业边缘场景下的 go-redis
数据库·redis·golang·边缘计算·工业网关
劲夫学编程15 小时前
leetcode: 字母异位词分组
算法·leetcode
wy_hhxx16 小时前
[Leetcode] 动态规划(打家劫舍、0-1背包、完全背包)
算法·leetcode·动态规划·完全背包·0-1背包
Shaoshing17 小时前
LeetCode100 32.最长有效括号
java·数据结构·leetcode
小白的高手之路17 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣