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)); } } }
以上是尋找數組/列表中的重複元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!