-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirstUnique.java
32 lines (24 loc) · 969 Bytes
/
FirstUnique.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
import java.util.*;
class FirstUnique {
public int solution(int[] A) {
Map<Integer, Integer> duplicatedCounts = countDuplicatedElements(A);
return findFirstUniqueElement(A, duplicatedCounts);
}
private Map<Integer, Integer> countDuplicatedElements(int[] A) {
Map<Integer, Integer> duplicatedCounts = new HashMap<>();
for (int element : A) {
Integer foundResult = duplicatedCounts.getOrDefault(element, 0);
duplicatedCounts.put(element, ++foundResult);
}
return duplicatedCounts;
}
private int findFirstUniqueElement(int[] A, Map<Integer, Integer> duplicatedCounts) {
for (int element : A) {
if (isDuplicateCountOne(duplicatedCounts, element)) return element;
}
return -1;
}
private boolean isDuplicateCountOne (Map<Integer, Integer> duplicatedCounts, int element) {
return duplicatedCounts.get(element) == 1;
}
}