question:
Given an array of integers, 1≤a[i]≤n (n = size of array) some elements appear twice and others appear.
Find all the elements which appear twice in this array.
Could do it without extra spaces and in O (n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
parsing:Method 1: According to the topic requirements: The validation array given up to two times the same number, or a certain number, the request does not open up space, time complexity is O (n). Because the array input features 1<=sums[i]<=n, you can use the original array as a hash table, because the original array is positive, marked with a negative number indicates that, if you encounter negative numbers that represent the second occurrence, you can find all the numbers that have occurred 2 times
public class Solution {public
list<integer> findduplicates (int[] nums) { int length = Nums. length;
list<integer> list = new arraylist<integer> ();
for (int i = 0; i < length; i++) {
int val = Math.Abs (Nums[i])-1;
if (Nums[val] > 0) {
Nums[val] =-nums[val];
} else {
List.add (Math.Abs (nums[i]));
}
return list;
}
Method 2: If you open up a large memory space, redefine an array, assign a value of 0, and then the original array of the number of the new array corresponding to the index, each time +1;
public class Solution {
Public list<integer> findduplicates (int[] nums) {
int length = Nums.length;
list<integer> list = new arraylist<integer> ();
if (length = = 0) {return
list;
} else {
int count[] = new Int[length];
Arrays.fill (count, 0);
for (int i = 0; i < length; i++) {
count[nums[i]-1]++;
}
for (int j = 0; J < length; J +) {
if (count[j] = = 2) {
List.add (j + 1);
}
}
return list;
}
}