Concise solution in Java


  • 0
    L

    n*(n+1)/2 to do a sum and subtracting the sum of the array to find the missing number is an obvious choice. However, the calculation to find the sum of numbers may cause overflow. A good idea is to use a bitset for optimization.

    public int missingNumber(int[] nums) {
            BitSet bit = new BitSet(nums.length);
            for(int i=0;i<nums.length;i++) {
                bit.set(nums[i]);
            }      
            return bit.nextClearBit(0);
        }
    

Log in to reply
 

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