【LeetCode】330. Patching Array 按要求补齐数组(Hard)(JAVA)每日一题

【LeetCode】330. Patching Array 按要求补齐数组(Hard)(JAVA)

题目地址: https://leetcode.com/problems/patching-array/

题目描述:

Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.

Example 1:

Input: nums = [1,3], n = 6
Output: 1 
Explanation:
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.

Example 2:

Input: nums = [1,5,10], n = 20
Output: 2
Explanation: The two patches can be [2, 4].

Example 3:

Input: nums = [1,2,2], n = 5
Output: 0

题目大意

给定一个已排序的正整数数组 nums,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。

解题方法

  1. 假如 [1, k] 是都是可以得到的和,对于下一个 k + 1,如何判断是否可以得到呢?
  2. 如果 k + 1 在 nums[i] 里面,那就是可以得到的,而且 [1 + k + 1, k + k + 1] 也可以得到([1, k] + (k + 1) 即可),合起来就是 [1, k + k + 1] 都可以得到;如果不在,当然就是丢失的数,也就是 k + 1 需要补上去,也同样可以得到相同的范围: [1, k + k + 1]
  3. 也就是对于下一个需要的值,先在 nums[i] 里面判断是否有,如果有的话,那就扩大了整个可以得到和的范围 +nums[i],否则,就算是丢失了一个
  4. 当然也会遇到 nums[i] 是在 [1, k] 上的值,那么 nums[i] <= k + 1, 都可以变为扩大的值,也就是 [1, k + nums[i]],因为 [1, k] + nums[i],而 [1, k] 都已经可以获得了
  5. note: 为了防止 int 超限用了 long 的值
class Solution {
    public int minPatches(int[] nums, int n) {
        long next = 1;
        int index = 0;
        int res = 0;
        while (next <= n) {
            if (index < nums.length && nums[index] <= next) {
                next += nums[index];
                index++;
            } else {
                next += next;
                res++;
            }
        }
        return res;
    }
}

执行耗时:1 ms,击败了10.42% 的Java用户
内存消耗:37.8 MB,击败了97.37% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/111879815