Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
当题目没那么多的限制时:
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
for (int num : nums) {
if (set.contains(num)) {
res.add(num);
} else {
set.add(num);
}
}
return res;
}
}
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
int []counts = new int[nums.length];
for (int num : nums) {
counts[num - 1] += 1;
}
for (int i = 0; i < nums.length; ++i) {
if (counts[i] > 1) {
res.add(i + 1);
}
}
return res;
}
}