题目
448. 找到所有数组中消失的数字
官方题解
方法一:使用额外数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int n = nums.size();
vector<bool> count(n + 1, false);
for (int i = 0; i < n; i ++) {
count[nums[i]] = true;
}
vector<int> res;
for (int i = 1; i <= n; i ++) {
if (!count[i]) {
res.push_back(i);
}
}
return res;
}
};
|
时间复杂度:O(N),其中 N 是数组 nums 的长度。我们需要遍历数组 nums 一次来标记出现的数字,然后再遍历一次 count 数组来找出消失的数字。
空间复杂度:O(N),需要额外的 count 数组来存储数字的出现情况。