Java simplest solution O(1) space O(n) time


  • 10
    Z

    Knowing n ^ n = 0 and n ^ 0 = n this would be very simple.

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

  • 0
    S

    Nice solution!


  • 0
    S

    I think we can take this problem as a MATH problem, the sum should be n*(n+1)/2, then minus each of the element in the array.

    public class Solution {
        public int missingNumber(int[] nums) {
            int n = nums.length;
            int sum = n*(n + 1)/2;
            for(int i : nums)
                sum-= i;
            return sum;
        }
    }
    

  • 0
    Z

    You might get an overflow when n is large enough. :)


  • 0
    M

    very good solution


Log in to reply
 

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