268. 缺失数字

https://leetcode-cn.com/problems/missing-number/

解法一:数学法

因为是从有序表[0, 1, 2, ... , n]中抠出一个数,因此可以用高斯求和公式先求出这n+1个数原本的和expectSum,减去题目所给数组的和,结果即为所求。复杂度o(n)

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    const expectSum = nums.length * (nums.length + 1) / 2    //原本的和
    let min = nums[0], max = nums[0], sum = 0
    for (let i in nums) {
        sum += nums[i]
    }
    return expectSum - sum
};

2021.10.6

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

最后更新于