Leetcode no. 330
2016-04-12 16:37
337 查看
330. 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
Example 1:
nums =
Return
Combinations of nums are
of:
Now if we add/patch
Possible sums are
So we only need
Example 2:
nums =
Return
The two patches can be
Example 3:
nums =
Return
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
2to 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
1patch.
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.
public class Solution { public int minPatches(int[] nums, int n) { long cover=1; int count=0, i=0; while (cover<= n){ if (i< nums.length && cover>= nums[i]) cover+= nums[i++]; else { count++; cover+= cover; } } return count; } }
相关文章推荐
- Maven pom.xml 配置详解
- 2.快速部署MySQL主从复制
- 4.MySQL 主主(m-m) 同步生产库标准同步操作实施流程
- ceph 块设备
- expect交互式脚本
- 图论复习笔记
- 53. Maximum Subarray
- Computer Hardware ID(CHID)及驱动推送
- Oracle内存结构
- Java 设计模式--策略模式
- android(NDK+JNI)---JNI字符串参数传递与返回值
- 安卓-获取图片/视频的缩略图
- Splunk公司在线笔试题(2016.4.12)
- 求数列的最大子段和的两种方法(包括时间复杂度为线性时间的算法)
- js中的call替代继承问题
- 关于 Android 混淆的一些心得
- jsoup
- 常用正则表达式
- 浙大 4月月赛
- pc相册制作,手机版相册制作