[LeetCode] Patching Array 补丁数组 Given a sorted positive integer arraynumsand an integern, 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: num...
Leetcode 330. Patching Array https://leetcode.com/problems/patching-array/description/ https://discuss.leetcode.com/topic/45320/c-8ms-greedy-solution-with-explanation 解题思路来自@Dragon.PW,表示感谢! Given a sorted positive integer array n......
Leetcode 330 Patching Array 题目大意: 给一个有序非负整数列nums和一个整数n,最少需要添加多少个数可以使得[1,n]间的每一个数都可以被数列中若干个数的和来表示。输出最小需要添加多少个数字。 Example 2: nums = [1, 5, 10], n = 20 Return 2. The two patches can be [2, 4]. 思路: 这...
https://leetcode.com/problems/patching-array/ 组合nums数组中的数字以填满[1, n]的范围,如果有空缺的组合数字,需要补patch到nums数组中,求最少需要几个patch。 https://leetcode.com/discuss/82822/solution-explanation 贪心,从小到大填满[1, n],能用原来的nums中的数的时候就用掉,不够就补patch。 举例...
Leetcode 330. Patching Array https://leetcode.com/problems/patching-array/description/ https://discuss.leetcode.com/topic/45320/c-8ms-greedy-solution-with-explanation 解题思路来自@Dragon.PW,表示感谢! Given a sorted positive integer array n......
参考资料:https://leetcode.com/discuss/82822/solution-explanation 代码 // Patching Array// Time complexity: O(n), Space complexity: O(1)publicclassSolution{publicintminPatches(int[]nums,intn){longmiss=1;intadded=0;inti=0;while(miss<=n){if(i<nums.length&&nums[i]<=miss){miss+=nums[i...
Using the given numbers 1, 2 and 4, we can already build all sums from 0 to 7, i.e., the range [0,8). But we can’t build the sum 8, and the next given number (13) is too large. So we insert 8 into the array. Then we can build all sums in [0,16). ...
My code: reference:https://discuss.leetcode.com/topic/35517/share-my-greedy-solution-by-java-with-simple-explanation-time-1-ms 我觉得这个思想还是很巧妙的。max 表示的是当前数字下,我能构成的最大数字,并且最小数字和最大数字之间是连续的。如果 max < nums[...
当前值nums[i]大于miss时,增加nums[i]并不能让集合覆盖[0, miss+nums[i]),此时最好的方法是加miss,使得范围增大到[0, 2 * miss)。 class Solution { public: int minPatches(vector<int>& nums, int n) { long miss = 1; int ret = 0, i = 0; ...
根据作者的例子:https://leetcode.com/problems/patching-array/discuss/78488/Solution-%2B-explanation nums = [1, 2, 4, 13, 43]andn = 100; 1,2,4可以得到1-7的和. 8没有了, 所以加上8. 因为前三个数字可以得到1-7, 那么加上8之后,就有 1-15(7+8) 的和. ...