Leetcode 268. Missing Number

Problem

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Algorithm

Sum all the numbers as x x x and use n ( n + 1 ) 2 − x \frac{n(n+1)}{2} - x 2n(n+1)x.

Code

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        sum_, n_ = 0, len(nums)
        for num in nums:
            sum_ += num
        return n_ * (n_ + 1) // 2 - sum_

你可能感兴趣的:(Leetcode,解题报告,入门题,leetcode,算法,职场和发展)