LeetCode.268. 缺失数字

给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。

示例 1:

输入: [3,0,1]
输出: 2

示例 2:

输入: [9,6,4,2,3,5,7,0,1]
输出: 8

说明:

你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?

思路1:

异或。对0-n进行异或将得到某一个确定的数字x,对这个数组的所有数字进行异或将得到一个确定的数字y,对x和y进行异或将得到这个缺失的数字。为了算法简洁,过程可以调整。

代码1:

class Solution:
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n=len(nums)
        for i in range(n):
            n^=nums[i]^i
        return n

分析1:

时间复杂度O(n),空间复杂度O(1)

思路2:

使用内置函数sum。将0-n的数字相加将得到一个数字a,将整个数组求和将得到一个数字b,两者之差即为所求。

代码2:

class Solution:
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        return n * (n + 1) // 2 - sum(nums)

分析2:

时间复杂度O(n),空间复杂度O(1)

猜你喜欢

转载自blog.csdn.net/u013942370/article/details/82931305
今日推荐