Home >Java >javaTutorial >Find the Duplicate Elements in an Array/List

Find the Duplicate Elements in an Array/List

DDD
DDDOriginal
2024-10-06 20:08:29905browse

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));
  }
 }
}



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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn