美文网首页
268. Missing Number

268. Missing Number

作者: April63 | 来源:发表于2018-06-25 11:26 被阅读0次

想法就是扫一遍,如果遇到nums[i] == len(nums)说名缺失的数字在中间,就在列表最后添加nums[i]然后顺序扫描交换使得每一位nums[i] = i或者nums[i] = len(nums)
最后扫描一遍数字,返回nums[i] != i的i或者返回最初的len(nums)

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        flag = len(nums)
        for i in range(len(nums)):
            if nums[i] == flag:
                nums.append(flag)
            while nums[i] != i and nums[i] != flag:
                temp = nums[i]
                nums[i] = nums[temp]
                nums[temp] = temp
        for i in range(len(nums)):
            if nums[i] != i:
                return i
        return flag
        

一种很神奇的异或运算、

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        xor = 0
        i = 0
        while i < len(nums):
            xor = xor ^ i ^ nums[i]
            i += 1
        return xor ^ i

相关文章

网友评论

      本文标题:268. Missing Number

      本文链接:https://www.haomeiwen.com/subject/lcaeyftx.html