Skip to content

Commit edbbbbb

Browse files
committed
剑指OfferII 004. 只出现一次的数字
1 parent a6c7c44 commit edbbbbb

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.gatsby.offerII;
2+
3+
import java.util.Arrays;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
7+
/**
8+
* @author -- gatsby
9+
* @date -- 2022/7/13
10+
* @description -- 剑指 Offer II 004. 只出现一次的数字
11+
*/
12+
13+
14+
public class _4OnlyOnce {
15+
public int singleNumber(int[] nums) {
16+
Map<Integer, Integer> count = new HashMap<>();
17+
for (int num : nums) {
18+
count.put(num, count.getOrDefault(num, 0) + 1);
19+
}
20+
21+
for (int num : count.keySet()) {
22+
if (count.get(num) == 1) return num;
23+
}
24+
25+
return -1;
26+
}
27+
28+
public int single(int start, int[] nums) {
29+
return nums[start] ^ nums[start + 1] ^ nums[start + 2];
30+
}
31+
32+
public int singleNumberSort(int[] nums) {
33+
Arrays.sort(nums);
34+
35+
for (int i = 0; i + 3 < nums.length; i += 3) {
36+
if (nums[i] != nums[i+2]) return single(i, nums);
37+
}
38+
return -1;
39+
}
40+
}

0 commit comments

Comments
 (0)