想法就是扫一遍,如果遇到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
网友评论