1238. 查找数组中的所有重复项
给定一个整数数组,1 ≤ a[i] ≤ n(n = 数组的大小),一些元素出现两次,其他元素出现一次。
找到在此数组中出现两次的所有元素。
样例
样例1
输入:
[4,3,2,7,8,2,3,1]
输出:
[2,3]
样例2
输入:
[10,2,5,10,9,1,1,4,3,7]
输出:
[1,10]
挑战
你可以在没有额外空间和O(n)运行时的情况下完成吗?
public class Solution {
/**
* @param nums: a list of integers
* @return: return a list of integers
*/
public List<Integer> findDuplicates(int[] nums) {
// write your code here
List<Integer> list=new ArrayList<>();
int[] dp=new int[nums.length+1];
for (int num : nums) {
dp[num]++;
if (dp[num] == 2) {
list.add(num);
}
}
return list;
}
}
public List<Integer> findDuplicates(int[] nums) {
// write your code here
List<Integer> list=new ArrayList<>();
HashSet<Integer> hashSet=new HashSet<>();
for (int num : nums) {
if (!hashSet.add(num)) {
if (!list.contains(num)) {
list.add(num);
}
}
}
return list;
}