按要求补齐数组——贪心

142 阅读1分钟

image.png image.png

代码:

对于正整数 x,如果区间 [1,x−1] 内的所有数字都已经被覆盖,且 x 在数组中,则区间 [1,2x−1] 内的所有数字也都被覆盖。

func minPatches(nums []int, n int) (patches int) {
    for i, x := 0, 1; x <= n; {
        if i < len(nums) && nums[i] <= x {
            x += nums[i]
            i++
        } else {
            x *= 2
            patches++
        }
    }
    return
}