# 448. Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤  n  ( n  = size of array), some elements appear twice and others appear once.

Find all the elements of [1,  n ] inclusive that do not appear in this array.

Could you do it without extra space and in O( n ) runtime? You may assume the returned list does not count as extra space.

Example:

``````Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]
``````

``````class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
int idx = abs(nums[i]) - 1;
nums[idx] = (nums[idx] > 0) ? -nums[idx] : nums[idx];
}
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > 0) {
res.push_back(i + 1);
}
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != nums[nums[i] - 1]) {
swap(nums[i], nums[nums[i] - 1]);
--i;
}
}
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != i + 1) {
res.push_back(i + 1);
}
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
int n = nums.size();
for (int i = 0; i < n; ++i) {
nums[(nums[i] - 1) % n] += n;
}
for (int i = 0; i < n; ++i) {
if (nums[i] <= n) {
res.push_back(i + 1);
}
}
return res;
}
};
``````

Find All Duplicates in an Array

First Missing Positive

https://discuss.leetcode.com/topic/65944/c-solution-o-1-space

https://discuss.leetcode.com/topic/66063/5-line-java-easy-understanding

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation