错误的集合

🎯 问题描述(来源于LeetCode)

集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。
给定一个数组 nums 代表了该集合发生错误后的结果。
请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

💻 代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
n=len(nums)
x,y=0,0
nums_count=[0]*(n+1)
for i in nums :
nums_count[i]+=1
for i in range(1,n+1):
if nums_count[i]==2:
x=i
if nums_count[i]==0:
y=i
return [x,y]

📊 性能分析

提交结果

  • 运行时间:7ms击败85.75%
  • 内存消耗:18.77MB击败60.97%

复杂度验证

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)