448. Find All Numbers Disappeared in an Array

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int n = nums.size();
// 4,3,2,7,8,2,3,1
// 1,2,2,2,3,4,7,8
// -4, -3, -2, -7, 8, 2, -3, -1
vector<int> ret;
for(int i=0;i<n;++i){
int idx = abs(nums[i])-1;
if(nums[idx]>0) nums[idx] *= (-1);
}
for(int i=0;i<n;++i){
if(nums[i]>0) ret.push_back(i+1);
}
return ret;
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)