06_缺失数字

2019-11-06  本文已影响0人  butters001
class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        i = 0
        for j in range(len(nums)):
            if i == nums[j]:
                i += 1
                continue
            return i
        return i


# leetcode 最优解
class Solution2(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        计算不缺失的正常和 - 真实的和 = 确实的数字   有意思
        """
        n = len(nums)
        expected_sum = (n + 1) * n / 2
        actual_sum = sum(nums)
        return expected_sum - actual_sum

上一篇 下一篇

猜你喜欢

热点阅读