Given an array of integers where 1≤a[i]≤ n (n = size of array), some elements appear twice a nd others appear once.
Find all the elements of [1, N] inclusive The does not appear in this array.
Could do it without extra space and in O (n) runtime? Assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
Idea:it ' s hard to solve without extra space and in O (n) without the condition 1≤a[i]≤ N.
Solution 1: for the number a[a[i]-1], if it was positive, assign it to its opposite number, else unchange it. The logic is if i+1 appear in the array, a[i] would be negative, so if a[i] are positive, i+1 doesn ' t appear in the array.
1 classSolution {2 Public:3vector<int> Finddisappearednumbers (vector<int>&nums) {4vector<int>Res;5 for(intI=0; I<nums.size (); i++){6 intIdx=abs (Nums[i])-1;7Nums[idx]= (nums[idx]>0)? (-Nums[idx]): Nums[idx];8 }9 for(intI=0; I<nums.size (); i++){Ten if(nums[i]>0) Res.push_back (i+1); One } A returnRes; - } -};
Solution 2:move Nums[i] from Positon I to their right position nums[i]-1, swap nums[i] and nums[nums[i]-1]. Finally, if I doesn ' t equal nums[i]-1, means i+1 doesn ' t appear in the array. Note the line 6-8
1 classSolution {2 Public:3vector<int> Finddisappearednumbers (vector<int>&nums) {4vector<int>Res;5 for(intI=0; I<nums.size (); i++){6 if(nums[i]!=nums[nums[i]-1]){7Swap (nums[i],nums[nums[i]-1]);8--i;9 }Ten } One for(intI=0; I<nums.size (); i++){ A if(i!=nums[i]-1){ -Res.push_back (i+1); - } the } - returnRes; - } -};
Solution 3:add Nums[nums[i]-1] to N, use (nums[i]-1)%n to avoid the overflow of nums[i]-1. Finally, if nums[i]<=n, I+1 is the disappeard number.
1 classSolution {2 Public:3vector<int> Finddisappearednumbers (vector<int>&nums) {4vector<int>Res;5 intSize=nums.size ();6 for(intI=0; i<size;i++){7nums[(nums[i]-1)%size]+=size;//mod to avoid overflow8 }9 for(intI=0; i<size;i++){Ten if(nums[i]<=size) { OneRes.push_back (i+1); A } - } - returnRes; the } -};
448. Find all Numbers disappeared in an Array