LeetCode 330 Patching Array

Refer: https://www.hrwhisper.me/leetcode-patching-array/

就是用known_sum表示已知的连续和为[1,known_sum),有了这个表示那就简单了:

  • nums[i] <= known_sum,更新已知范围为:[1,known_sum + nums[i] )
  • nums[i] >  known_sum,  添加known_sum进数组才能达到最大的范围,所以已知范围更新为:[1,known_sum *2  )

 

    // refer: https://www.hrwhisper.me/leetcode-patching-array/
    public int minPatches(int[] nums, int n) {
        int i = 0;
        int cnt = 0;
        long knownSum = 1;
        while(knownSum <= n) {
            if(i < nums.length && nums[i] <= knownSum) {
                knownSum += nums[i];
                i++;
            } else {
                knownSum *= 2;
                cnt++;
            }
        }
        
        return cnt;
    }

 

你可能感兴趣的:(LeetCode 330 Patching Array)