最初想法
def findErrorNums(nums):
n = len(nums)
duplicate = -1
missing = -1
for num in nums:
if nums[abs(num) - 1] < 0:
duplicate = abs(num)
else:
nums[abs(num) - 1] *= -1
for i in range(n):
if nums[i] > 0:
missing = i + 1
break
return [duplicate, missing]
遇到力扣大佬
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n=len(nums)
S=sum(set(nums))#set()返回列表中独特的数,比如输入[1,2,2,4]会返回[1,2,4]
return [sum(nums)-S,n*(n+1)//2-S]#后者代表1-N求和
我擦,被秒了