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]
Title tag: The array topic gives us a nums array with some numbers appearing two times and the rest appearing only once, allowing us to find all the repetitions two times. Because this topic does not stipulate that we cannot change the array, we can map num in array to nums[Num-1] one-to-two mappings, and each time we encounter a num, we change the corresponding position num to the-num mark. If you encounter a duplicate, it must have been tagged with the same number.
Java Solution:
Runtime beats 85.92%
Completion Date: 09/19/2017
Keywords: Array
Key point: Make Num and num[num-1] 1-to-1 mappings
1 classSolution2 {3 PublicList<integer> Findduplicates (int[] nums)4 {5List<integer> duplicates =NewArraylist<>();6 7 for(intnum:nums)8 {9 intAbsnum =math.abs (num);Ten One if(Nums[absnum-1] < 0)//If the number at position num-1 is already negative ADuplicates.add (Absnum);//num is duplicate - Else -NUMS[ABSNUM-1] *=-1; the } - - returnduplicates; - } +}
Resources:
Https://discuss.leetcode.com/topic/64735/java-simple-solution
Leetcode List of topics- leetcode Questions List
Leetcode 442. Find all duplicates in an array (finds all duplicates in the array)