Home > Java > javaTutorial > body text

Find the Duplicate Elements in an Array/List

DDD
Release: 2024-10-06 20:08:29
Original
771 people have browsed it

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



Copy after login

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!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!