1 public class Solution {
 2     public int minPatches(int[] nums, int n) {
 3         long missed = 1;
 4         int index = 0;
 5         int result = 0;
 6         while (missed <= n) {
 7             if (index < nums.length && nums[index] <= missed) {
 8                 missed += nums[index++];
 9             } else {
10                 missed += missed;
11                 result++;
12             }
13         }
14         return result;
15     }
16 }

 

Code is simple. But the logic is:

1. start search from [1, n], when you find a number in nums that less than missed, add it to missed. Then you can form (1, missed + nums[i]) range.

2. If you dont find it, it is better to add missed it self. Because from last time, you already can form (1, missed) range. You cannot form a range larger than (1, missed + missed) with one element adding. Why?

For example:

if you have (1, missed), adding another number x. You are trying to form [1, missed + x) range sum. Ok, here we have [1, missed) now. What we are missing? this missed number it self. Using current number set cannot form missed. Thus missed is the largest number we can add.

posted on 2016-07-01 16:09  keepshuatishuati  阅读(228)  评论(0编辑  收藏  举报