ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

330. Patching Array

2019-08-04 16:55:06  阅读:263  来源: 互联网

标签:13 nums 28 43 Patching 330 Array 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


1 class Solution { 2 public: 3 int minPatches(vector<int>& nums, int n) { 4 long miss = 1, added = 0, i = 0; 5 while (miss <= n) { 6 if (i < nums.size() && nums[i] <= miss) { 7 miss += nums[i++]; 8 } else { 9 miss += miss; 10 added++; 11 } 12 } 13 return added; 14 } 15 };

 

开始以为是dp, 看了答案发现是贪心  差不多10行. 感觉全方面受到了打击.

贪心算法是看懂了, 不过并没有搞懂为什么这样就是最少的解法呢...

 

给数组加上数字, 以便于可以得到1-n所有数字的和. 并且要加入的数字最少.

贪心策略就是从1开始扫描,缺哪个补哪个...

 

根据作者的例子: https://leetcode.com/problems/patching-array/discuss/78488/Solution-%2B-explanation

nums = [1, 2, 4, 13, 43] and n = 100;

1,2,4可以得到1-7的和. 8没有了, 所以加上8.

因为前三个数字可以得到1-7, 那么加上8之后,就有 1-15(7+8) 的和.

但是注意一下, 1-15 里面的13 是原数组本来就有的, 所以实际上我们可以得到1-28(15+13).

再检查原数组, 自13以后, 原数组没有包含任何一个属于1-28的数字, 此轮贪心结束了.

 

第二轮贪心, 下一个数字是43, 比28大的多,因此加上29. 于是我们可以得到1-57(28+29). 

原数组又包含了43, 所以实际上可以得到1-100(57+43). 结束

 

一共添加了8,29 两个数字....简直卧槽

标签:13,nums,28,43,Patching,330,Array,array,贪心
来源: https://www.cnblogs.com/lychnis/p/11298692.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有