forked from kdn251/interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleNumberII.java
More file actions
27 lines (23 loc) · 780 Bytes
/
SingleNumberII.java
File metadata and controls
27 lines (23 loc) · 780 Bytes
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
//Given an array of integers, every element appears three times except for one,
//which appears exactly once. Find that single one.
//Note:
//Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class SingleNumberII {
public int singleNumber(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i: nums) {
if(map.containsKey(i)) {
map.put(i, map.get(i) + 1);
} else {
map.put(i, 1);
}
}
for(int key: map.keySet()) {
if(map.get(key) == 1) {
return key;
}
}
//no unique integer in nums
return -1;
}
}