Easy 1ms JAVA solution


  • 0
    G
    public int missingNumber(int[] nums) {
        int total = 0;
        for(int i = 1; i<=nums.length; i++){
            total = total+i-nums[i-1];
        }  
        return total;
    }

  • 0
    K

    What if nums[0] = Integer.MAX_INTEGER and nums[1] = Integer.MAX_INTEGER-1,
    the value of total will be underflow....


  • 0
    J

    Use average instead of total sum just avoid overflow.


  • 0
    J

    Yeah, this is going to overflow if nums.length is greater than about 2*sqrt(Integer.MAX_VALUE). As a quick workaround, just make total be a long. Here is my similar solution:

    public class Solution {
        public int missingNumber(int[] nums) {
            if (null == nums) {
                return 0;
            }
            
            long all = 0;
            long present = 0;
            for (int i=0; i<nums.length; ++i) {
                all += i;
                present += nums[i];
            }
            return (int)(all-present + nums.length);
        }
    }
    

Log in to reply
 

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