Java Solution Missing Number


  • 0
    I
    public static int missingNumber(int[] nums) {
    	int res = 0;
    	Arrays.sort(nums);
    	if (nums[0] == 0 && nums.length == 1) {
    		res = 1;
    	} else {
    		if (nums.length > 1) {
    			for (int i = 0; i < nums.length; i++) {
    				if (i != nums[i]) {
    					res = nums[i] - 1;
    					break;
    				} else {
    					res = nums[nums.length - 1] + 1;
    				}
    			}
    		} else {
    			res = nums[0] - 1;
    		}
    	}
    	System.out.println(res);
    	return res;
    }

  • 1
    A
    public int missingNumber(int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] != i && nums[i] < nums.length) {
                int temp = nums[i];
                nums[i] = nums[nums[i]];
                nums[temp] = temp;
            }
        }
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != j)
                return j;
        }
        return nums.length;
    }
    

    Since each element would only be placed on its right position once, thus would not enter the while loop.
    The overall time complexity O(n).


  • 7
    D
    public int missingNumber(int[] nums) {
            
            int l = nums.length;
            int sum = (l*(l+1))/2;
            for(int i = 0 ; i < l; i++){
                sum -= nums[i];
            }
            return sum;
        }
    

    Since the numbers in the array would be between 0 to n, with only one number missing, we first find the sum of the elements including the missing number. This can be done in O(1) by using the formula (n*(n+1))/2 (sum of natural numbers). All we need to do now is compute the sum of the given elements in the array and the difference between this sum and the sum derived from the formula would be the answer.


  • 0
    B

    How about this code?

    public int missingNumber(int[] nums) {
        int trueSum = 0;
        int fakeSum = 0;
        
        int i = 0;
        while(i < nums.length){
            trueSum += nums[i];
            fakeSum += i;
            i++;
        }
        
        if(trueSum == fakeSum){
            return i;
        }else{
            return (fakeSum+i)-trueSum;
        }
    }
    

    Similar to the others, but with a slightly different approach.


  • 0
    E

    Good answer! Thanks


Log in to reply
 

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