Given an array of integers, 1≤a[i]≤ n (n = size of array), some elements appear twice and others AppE AR once.
Find all the elements, appear twice in this array.
Could do it without extra space and in O (n) runtime?
Example:
input:[4,3,2,7,8,2,3,1]output:[2,3]
When you look for duplicates, think of a hash table first. O (n) time complexity is simple, as long as the traversal into the hash table, and then the result is shown. But this does not meet the requirements of space complexity. In general, time and space are required for trade off. Keep time constant and reduce space, there must be other mystery in it. This problem is so, see the qualification 1≤a[i]≤ n , know that the A[i]-1 range is 0~n, then it can actually be used as the subscript of the array. That is, the array elements and arrays are actually the corresponding relationships (looks like nonsense ...). )。 Each time an element is accessed and a subscript is accessed, the corresponding subscript is accessed again when the element is accessed again. This makes it possible to make a fuss over the element that corresponds to its subscript. Is there any way to make an element that can act as a marker, without affecting its ability to continue to do subscript properties? That is to take a negative number. This means that if the element corresponds to an element pointing to a negative number, you know that the element has already occurred. Taking a negative number does not affect the property of the subscript, because it is good to take the absolute value. So the essence is not that the tag traverses the element itself, but the element that is traversed with the minus sign marks the element to which the subscript points. Or you can think of itself as a hash table, the process of calculating the hash is also the process of marking.
Java
classSolution { PublicList<integer> Findduplicates (int[] nums) {List<Integer> res =NewArraylist<>(); if(Nums = =NULL|| Nums.length = = 0)returnRes; for(inti = 0; i < nums.length; i++) { intindex = Math.Abs (Nums[i])-1; if(Nums[index] > 0) nums[index] *=-1; Else{res.add (index+ 1); Index + 1 = = Math.Abs (Nums[i])}}returnRes; }}
(Java) Leetcode 442. Find all duplicates on an array--array of repeated data