-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindAllDuplicatesInAnArray.java
53 lines (42 loc) · 1.32 KB
/
FindAllDuplicatesInAnArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.leetcode.algorithms.medium.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
public class FindAllDuplicatesInAnArray {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
int[] nums = InputUtil.integerArr(inputs);
List<Integer> collResult = findDuplicates(nums);
// Print result
int[] arrResult = new int[collResult.size()];
for(int i = 0; i < collResult.size(); i++) {
arrResult[i] = collResult.get(i);
}
System.out.println(Arrays.toString(arrResult));
scanner.close();
}
private static List<Integer> findDuplicates(int[] nums) {
// Store duplicate key in map into list
List<Integer> result = new ArrayList<>();
// Count every number and store it into map
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if (i == 0) {
map.put(nums[i], 1);
} else {
if(map.containsKey(nums[i]) && !result.contains(nums[i])) {
result.add(nums[i]);
} else {
map.put(nums[i], 1);
}
}
}
return result;
}
}