Advertisement
gelita

Get Duplicates

Feb 8th, 2020
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.30 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. class MyCode {
  4.  
  5.  
  6.    /**
  7.     *  Get Duplicates
  8.     *
  9.     *  Given an array of values, return only the values that have duplicates in the
  10.     *  array
  11.     *
  12.     *  Parameters
  13.     *  Input: arr {Array}
  14.     *  Output: {ArrayList}
  15.     *
  16.     *  Constraints
  17.     *  Time: O(N)
  18.     *  Space: O(N)
  19.     *
  20.     *  Examples
  21.     *  [1, 2, 4, 2] --> [2]
  22.     *  [3, 2, 3, 2, 3, 3, 4] --> [3, 2]
  23.     *  [1, 2, 3, 4] --> []
  24.     */
  25.     public static void main (String[] args) {
  26.     int[] arr = new int[]{1, 2, 3, 4};
  27.   ArrayList<Integer> l= new ArrayList<Integer>();
  28.   l = getDuplicates(arr);
  29.  
  30.   }
  31.    
  32.    public static ArrayList<Integer> getDuplicates(int[] arr) {
  33.       HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  34.       ArrayList<Integer> list = new ArrayList<Integer>();
  35.       int count= 0;
  36.       for(int i = 0; i<arr.length; i++){
  37.         if(map.containsKey(arr[i])){
  38.             count = map.get(arr[i]);
  39.             map.put(arr[i],++count);
  40.         }else{          
  41.             map.put(arr[i], 1);  
  42.         }
  43.       }
  44.       for(Map.Entry<Integer,Integer> entry: map.entrySet()){
  45.           if(entry.getValue() > 1){
  46.             list.add(entry.getKey());
  47.           }
  48.       }
  49.       System.out.println(list);
  50.       return list;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement