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
}
相关推荐
Pniubi9 小时前
力扣76.最小覆盖子串
算法·leetcode·职场和发展
文丑颜不良啊14 小时前
LeetCode2541~2560题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2481~2500题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2521~2540题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2501~2520题目解析
java·leetcode
Pniubi2 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
利威尔xu3 天前
Go map 底层崩溃:3 个 goroutine 并发写同一张 map,fatal error 崩掉整个服务
golang·源码·map·并发·后端开发
Rain的Java大神之路3 天前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode