java 330. Patching Array(1st).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 330. Patching Array(1st).java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int minPatches(int[] nums, int n) {
        long end = 0; // [1,2,31,33] 2147483647 => 28
        int i = 0;
        int count = 0;
        while (i < nums.length) {
            if (end >= n) {
                return count;
            }
            if (nums[i] <= end + 1) {
                end += nums[i++];
            } else {
                count++;
                end += end + 1;
            }
        }
        while (end < n) { // [] 7 => 3
            end += end + 1;
            count++;
        }
        return count;
    }
}
public class Solution {
    public int minPatches(int[] nums, int n) {
        long range = 1;//the max val that can get in the current nums in the array.
		int add = 0;
		int i = 0;
		while(range <= n){
			if(i < nums.length && nums[i] <= range){
				range += nums[i++];
			}
			else{
				add++;
				range *= 2;
			}
		}
		return add;    
    }
}

以上是关于java 330. Patching Array(1st).java的主要内容,如果未能解决你的问题,请参考以下文章

java 330. Patching Array(1st).java

java 330. Patching Array(1st).java

java 330. Patching Array(1st).java

java 330. Patching Array(1st).java

330. Patching Array

Leetcode 330: Patching Array