Topic
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 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]
Analysis
An n-bit integer array that should contain all of the 1~n, actually missing some of them, to find out the missing numbers.
Constraints: No additional space (except for the returned list), Time complexity O (n)
Solution 1: The array subscript +1 as a "new array", the corresponding subscript +1 is marked as negative, unmarked subscript +1 is the number of non-occurrences(18ms)
Iterates through an array, and encounters 4 modifies the 4th number in the array (subscript 3) to a negative
Traversing the array again, if the number of M (subscript m-1) is not modified to a negative number, meaning M is missing in the array
Cases:
1 2 3 4 5 6 7 8 (subscript + 1)
4 3 2 7 8 2 3 1
-4-3-2-7 8 2-3-1
1 Public classSolution {2 PublicList<integer> Finddisappearednumbers (int[] nums) {3list<integer> list =NewArraylist<integer>();4 for(inti = 0; i < nums.length; i++){5Nums[math.abs (Nums[i])-1] =-Math.Abs (Nums[math.abs (nums[i))-1]);6 //internal absolute value: when traversing to a number that has been marked as negative, use its absolute value to find the subscript7 //the most external absolute value: Repeated occurrences of the number, subscript has been marked once, and then directly to the opposite number will become positive, you need to first absolute value to seek the opposite number8 }9 for(inti = 0; i < nums.length; i++){Ten if(Nums[i] > 0){ OneList.add (i + 1)); A } - } - returnlist; the } -}
Solution 2: The 5th line in Solution 1 is unwrapped(17ms√)
1 Public classSolution {2 PublicList<integer> Finddisappearednumbers (int[] nums) {3list<integer> list =NewArraylist<integer>();4 for(inti = 0; i < nums.length; i++){5 intindex = Math.Abs (Nums[i])-1;6 if(Nums[index] > 0)7Nums[index] =-Nums[index];8 }9 for(inti = 0; i < nums.length; i++){Ten if(Nums[i] > 0){ OneList.add (i + 1)); A } - } - returnlist; the } -}
448. Find all Numbers disappeared in an Array