Given an array of integers, find all the elements that are duplicated.
Example:
Input: [1, 2, 3, 4, 3, 2, 5]
Output: [2, 3]
Hint:
You can use a HashSet to track elements you have already seen. If an element is already in the set, it's a duplicate. For preserving order, use LinkedHashSet to store the duplicates.
Java Code Using HashSet
import java.util.Arrays; import java.util.HashSet; import java.util.List; public class Test { public static void main(String[] args) { List<Integer> li = Arrays.asList(1, 2, 3, 4, 3, 2, 5); HashSet<Integer> hs = new HashSet<Integer>(); for (int i = 0; i < li.size(); i++) { if (hs.contains(li.get(i))) { System.out.println(li.get(i)); } hs.add(li.get(i)); } } }
The above is the detailed content of Find the Duplicate Elements in an Array/List. For more information, please follow other related articles on the PHP Chinese website!