[LeetCode][JavaScript]Patching Array
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode][JavaScript]Patching Array相关的知识,希望对你有一定的参考价值。
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:
nums = [1, 3]
, n = 6
Return 1
.
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:
nums = [1, 5, 10]
, n = 20
Return 2
.
The two patches can be [2, 4]
.
Example 3:
nums = [1, 2, 2]
, n = 5
Return 0
.
https://leetcode.com/problems/patching-array/
组合nums数组中的数字以填满[1, n]的范围,如果有空缺的组合数字,需要补patch到nums数组中,求最少需要几个patch。
https://leetcode.com/discuss/82822/solution-explanation
贪心,从小到大填满[1, n],能用原来的nums中的数的时候就用掉,不够就补patch。
举例来说,nums = [1, 5, 10], n = 40。
首先就缺少了2,patch补2,此时范围是[1, 3],即1 ∪ 2 ∪ 1 + 2。
这边还用不到5,patch补4,此时范围是[1, 7],即[1, 3] ∪ 4 ∪ [1 + 4, 3 + 4] 。
5在的[1, 7]的范围里,可以用上5,此时范围是[1, 12],即[1, 7] ∪ [1 + 5, 7 + 5] 。
10在的[1, 12]的范围里,用上10,此时范围是[1, 22],即[1, 12] ∪ [1 + 10, 12 + 10] 。
patch补23,此时范围是[1, 45],即[1, 22] ∪ 23 ∪ [1 + 23, 22 + 23] 。
最后需要3个patch[2, 4, 23]。
代码按照这个思路实现,先看nums里的数能不能用上,如果不行就加一个patch。
1 /** 2 * @param {number[]} nums 3 * @param {number} n 4 * @return {number} 5 */ 6 var minPatches = function(nums, n) { 7 var countPatch = 0, numsIndex = 0; 8 for(var i = 1; i <= n;){ 9 if(nums[numsIndex] < i){ 10 i += nums[numsIndex]; 11 numsIndex++; 12 continue; 13 } 14 if(nums[numsIndex] === i) 15 numsIndex++; 16 else 17 countPatch++; 18 if(i - 1 > 0) 19 i += i - 1; 20 i++; 21 } 22 return countPatch; 23 };
以上是关于[LeetCode][JavaScript]Patching Array的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode4. Median of Two Sorted Arrays---vector实现O(log(m+n)--- findkth
[JavaScript 刷题] 双指针 - leetcode 142 & leetcode 287
[JavaScript 刷题] 双指针 - leetcode 142 & leetcode 287
javascript [242。有效Anagram] #tags:leetcode,leetcode / easy