-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOnceNumberII.java
More file actions
54 lines (35 loc) · 1.04 KB
/
OnceNumberII.java
File metadata and controls
54 lines (35 loc) · 1.04 KB
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
package array_and_matrix;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: Wenhang Chen
* @Description:给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。 说明:
* <p>
* 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
* <p>
* 示例 1:
* <p>
* 输入: [2,2,3,2]
* 输出: 3
* 示例 2:
* <p>
* 输入: [0,1,0,1,0,1,99]
* 输出: 99
* @Date: Created in 19:37 6/19/2020
* @Modified by:
*/
public class OnceNumberII {
public int singleNumber(int[] nums) {
if (nums == null || nums.length < 1)
return 0;
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1)
return entry.getKey();
}
return 0;
}
}