[C#] Simple, fast solution without integer overflow risk


  • 1
    N
    public int MissingNumber(int[] nums) {
        int result = 0;
        int n = nums.Length;
        for (int i = 0; i < n; i++) {
            result += (i - nums[i]);
        }
        result += n;
        return result;
    }

  • 0
    M

    It can still overflow. For example, input is [2000000000, 2000000001, 2000000002, ...]


  • 0
    N

    You're right. I wrongly assumed that the 0..n input array would be sorted. That will teach me not to be so overconfident!


Log in to reply
 

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