Missing Number


  • 0

    Click here to see the full article post


  • 0
    J

    Approach #3, Approach #4 For the first time,I saw these kind of thinking to solve question. Brilliant!


  • 0
    S

    regarding Approach #3, I believe this will only work if:
    index 0 and num 0,
    index 1 has num 1,
    index 5 has num 5,
    index 9 has num 9
    etc...

    what if index 0 has 251
    index 1 has 267
    index 2 has 305
    etc???

    @jjsomiya - what do you think ?


  • 0

    @seakhar The numbers do not have to be in order because XOR is a commutative function.

    However, your second example does not fit the constraints of the problem (unless the array is at least 305 elements long). See: "n distinct numbers taken from 0, 1, 2, ..., n"


  • 0
    J
    This post is deleted!

  • 0
    M

    private int[] Sortarray(int[] array)
    {
    for(int x = 0; x < array.Length; x++)
    {
    for(int y = x; y < array.Length; y++)
    {
    if(array[y] < array[x])
    {
    int a = array[x];
    array[x] = array[y];
    array[y] = a;
    }
    }
    }
    return array;
    }

        public int FindMissingNumber(int[] array)
        {
            int value = 0;
            array = (Sortarray(array));
            for(int x = 0; x <  array.Length; x++)
            {
                if(x < array.Length)
                {
                    if(array[x + 1] == array[x] + 1)
                    {
                        continue; 
                    }
                    else
                    {
                        value = array[x] + 1;
                        x = array.Length;
                    }
    
                }
            }
            return value;
        }

  • 0
    J

    simple C++ solution

    int missingNumber(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            for(int i = 0; i <= nums.size(); i++)
                if(nums[i] != i)
                    return i;
        }
    

  • 0
    L

    Short java answer:

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

  • 0
    W

    class Solution(object):
    def missingNumber(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    return sum(range(len(nums)+1)) - sum(nums)


Log in to reply
 

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