[LeetCode] 贪心算法之 Patching Array
来源:互联网 发布:nginx error log 配置 编辑:程序博客网 时间:2024/05/20 16:36
题目
分析
这是一道典型的贪心算法,非常的好。大意是:给我们一个数组和一个值n,让我们用这个数组里面的任意多个元素和,构造出[1,n]的序列。注意:最大值大于n即可,没有强调一定要恰好是n,所以这就是可以使用贪心算法的关键。
首先我们的角度不要从给定的数组入手,而是从生成的序列。考虑如果目前已经考虑的数组里面的值,可以构造的范围是[a,b](b < n),那么,我们下一个想要的值就是b+1,因此,考虑下一个nums[i+1],如果nums[i+1] = c <= b+1,那么,就可以和之前的构造出[a, b+c]的数组。如果nums[i+1] > b+1,那么这个数组就会出现断层,变成[a, b] | [c, b+c],所以此时,我们不能加入nums[i+1],而是补一个值为b+1的数,才能构造出来目标的数组。以此循环,直至max>=n,即可完成。
时间复杂度分析
考虑数组nums的size为m,则时间复杂度最多不会超过O(m+n)
代码
class Solution {public: int minPatches(vector<int>& nums, int n) { unsigned long max = 0, count = 0; for (int i = 0; max < n;) { // 下一个要包括进去的是max+1,如果nums[i]已经在max+1的范围之内,那么就将他加进集合,并且扩充max的范围。 if (i < nums.size() && nums[i] <= max+1) { max += nums[i]; i++; } //此时,由于nums[i] > max +1,那么就会遗漏max+1这个值,因此需要将max+1这个值填充进去。 else { max += max+1; count++; } } return count; }};
阅读全文
0 0
- [LeetCode] 贪心算法之 Patching Array
- leetcode 330. Patching Array-数组补丁|贪心算法
- leetcode 330 : Patching Array :贪心法
- 330. Patching Array-数组补丁|贪心算法
- LeetCode330. Patching Array【贪心】
- leetcode330:Patching Array(贪心)
- leetcode Patching Array
- [LeetCode] Patching Array
- leetcode笔记:Patching Array
- Leetcode: Patching Array
- leetcode 330. Patching Array
- Leetcode Patching Array
- [leetcode]330. Patching Array
- [LeetCode]330. Patching Array
- [LeetCode 330] Patching array
- 【LeetCode-330】Patching Array
- LeetCode Patching Array
- LeetCode Patching Array
- Python基础
- win10安装oracle11g无法打开数据库oracle not available
- 在 CentOS7 上安装 zookeeper-3.4.9 服务 1、创建 /usr/local/services/zookeeper 文件夹: mkdir -p /usr/local/s
- 遗传算法原理
- VC++动态链接库(DLL)编程深入浅出
- [LeetCode] 贪心算法之 Patching Array
- HashMap的实现原理和底层结构
- Struts2动态方法调用案例
- pycaffe 配置与安装-Linux平台
- pageContext对象
- 设计模式之适配器模式
- Lyft的TypeScript实践
- 使用acs-engine在Azure中国区部署kubernetes集群详解
- Android 选择图片或视频 ,循环播放