码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 330: Patching Array

时间:2017-12-10 11:19:05      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:UI   bsp   and   patch   required   amp   array   sorted   ted   

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

 

 1 public class Solution {
 2     public int MinPatches(int[] nums, int n) {
 3         
 4         int i = 0, patches = 0;
 5         long max = 1;
 6         
 7         while (max <= n)
 8         {
 9             if (i < nums.Length && nums[i] <= max)
10             {
11                 max += nums[i];
12                 i++;
13             }
14             else
15             {
16                 max += max;
17                 patches++;
18             }
19         }
20         
21         
22         return patches;
23     }
24 }

 

Leetcode 330: Patching Array

标签:UI   bsp   and   patch   required   amp   array   sorted   ted   

原文地址:http://www.cnblogs.com/liangmou/p/8016088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!