"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Find the Duplicate Elements in an Array/List

Find the Duplicate Elements in an Array/List

Published on 2024-11-03
Browse:283

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 li = Arrays.asList(1, 2, 3, 4, 3, 2, 5);
  HashSet hs = new HashSet();
  for (int i = 0; i 


          

        
Release Statement This article is reproduced at: https://dev.to/realnamehidden1_61/find-the-duplicate-elements-in-an-arraylist-380a?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3