首頁  >  文章  >  Java  >  尋找數組/列表中的重複元素

尋找數組/列表中的重複元素

DDD
DDD原創
2024-10-06 20:08:29827瀏覽

Find the Duplicate Elements in an Array/List

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn