Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class MyCode {
- /**
- * Get Duplicates
- *
- * Given an array of values, return only the values that have duplicates in the
- * array
- *
- * Parameters
- * Input: arr {Array}
- * Output: {ArrayList}
- *
- * Constraints
- * Time: O(N)
- * Space: O(N)
- *
- * Examples
- * [1, 2, 4, 2] --> [2]
- * [3, 2, 3, 2, 3, 3, 4] --> [3, 2]
- * [1, 2, 3, 4] --> []
- */
- public static void main (String[] args) {
- int[] arr = new int[]{1, 2, 3, 4};
- ArrayList<Integer> l= new ArrayList<Integer>();
- l = getDuplicates(arr);
- }
- public static ArrayList<Integer> getDuplicates(int[] arr) {
- HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
- ArrayList<Integer> list = new ArrayList<Integer>();
- int count= 0;
- for(int i = 0; i<arr.length; i++){
- if(map.containsKey(arr[i])){
- count = map.get(arr[i]);
- map.put(arr[i],++count);
- }else{
- map.put(arr[i], 1);
- }
- }
- for(Map.Entry<Integer,Integer> entry: map.entrySet()){
- if(entry.getValue() > 1){
- list.add(entry.getKey());
- }
- }
- System.out.println(list);
- return list;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement