题目链接:442. 数组中重复的数据 - 力扣(LeetCode)
解题思路:
利用set的特性(set里存放的都是不重复的数据),因为数组中的数据只出现一次或两次,所以直接将出现两次的数据放到list结果中,即得所求。
题解:
public static List<Integer> findDuplicates(int[] nums){
List<Integer>ans=new ArrayList<>();
Set<Integer>set=new HashSet<>();
for (int num : nums) {
if (!set.add(num)) {
ans.add(num);
}
}
return ans;
}
测试样例:
int[] nums={4,3,2,7,8,2,3,1};
运行结果:
2 3
Process finished with exit code 0