Share my simple Java code


  • 4
    M
    public class Solution {
        public int minPatches(int[] nums, int n) {
            int count = 0, i = 0;
            for (long covered=0; covered < n; ) {
                if ((i<nums.length && nums[i]>covered+1) || i>=nums.length) {  // at this moment, we need (covered+1), patch it.
                    covered += covered+1;
                    ++count;
                } else { covered += nums[i++]; }
            }
            return count;
        }
    }

  • 0
    G

    Amazing solution! Code is easy to understand, adding the missing number.
    but I think the key is to explain and prove this works..not just passing the OJ ,but come up a math explanation during the interview.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.