[LeetCode] Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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] = -(abs(nums[idx]));
}
for(int i = 0; i < nums.size(); i++) {
if(nums[i] > 0) res.push_back(i+1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/find-all-numbers-disappeared-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.