These two questions are interesting, because the elements are 1~n, so the value of each element-1 (mapped to 0~n-1) can be directly used as subscript. This will be nums in the corresponding subscript element *-1 with I means index+1 this element has appeared, can save storage space.
448. Find all Numbers disappeared in an Array
classSolution { Public: Vector<int> Finddisappearednumbers (vector<int>&nums) { for(intI=0; I<nums.size (); + +i) { intIndex=abs (Nums[i])-1; if(nums[index]>0) nums[index]*=-1; } Vector<int>Res; for(intI=0; I<nums.size (); + +i) { if(nums[i]>0) Res.push_back (i+1); } returnRes; }};
442. Find all duplicates in an Array
classSolution { Public: Vector<int> Findduplicates (vector<int>&nums) {Vector<int>Res; for(intI=0; I<nums.size (); + +i) { intIndex=abs (Nums[i])-1; if(nums[index]>0) nums[index]*=-1; ElseRes.push_back (index+1); } returnRes; }};
Leetcode 448. Find all Numbers disappeared in an Array & 442. Find all duplicates in an Array