Skip to content

Commit 9dd87cb

Browse files
refactor 137
1 parent da5abf6 commit 9dd87cb

File tree

1 file changed

+29
-35
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+29
-35
lines changed

src/main/java/com/fishercoder/solutions/_137.java

+29-35
Original file line numberDiff line numberDiff line change
@@ -3,45 +3,39 @@
33
import java.util.HashMap;
44
import java.util.Map;
55

6-
/**
7-
* 137. Single Number II
8-
9-
Given an array of integers, every element appears three times except for one. Find that single one.
10-
11-
Note:
12-
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
13-
*/
146
public class _137 {
157

16-
public static class Solution1 {
17-
public int singleNumber(int[] nums) {
18-
Map<Integer, Integer> map = new HashMap();
19-
for (int i : nums) {
20-
map.put(i, map.getOrDefault(i, 0) + 1);
21-
}
22-
for (int key : map.keySet()) {
23-
if (map.get(key) != 3) {
24-
return key;
8+
public static class Solution1 {
9+
public int singleNumber(int[] nums) {
10+
Map<Integer, Integer> map = new HashMap();
11+
for (int i : nums) {
12+
map.put(i, map.getOrDefault(i, 0) + 1);
13+
}
14+
for (int key : map.keySet()) {
15+
if (map.get(key) != 3) {
16+
return key;
17+
}
18+
}
19+
return 0;
2520
}
26-
}
27-
return 0;
2821
}
29-
}
3022

31-
public static class Solution2 {
32-
/** Credit: https://discuss.leetcode.com/topic/11877/detailed-explanation-and-generalization-of-the-bitwise-operation-method-for-single-numbers/2 */
33-
public int singleNumber(int[] nums) {
34-
int counter1 = 0;
35-
int counter2 = 0;
36-
int mask = 0;
37-
for (int num : nums) {
38-
counter2 ^= counter1 & num;
39-
counter1 ^= num;
40-
mask = ~(counter1 & counter2);
41-
counter1 &= mask;
42-
counter2 &= mask;
43-
}
44-
return counter1;
23+
public static class Solution2 {
24+
/**
25+
* Credit: https://discuss.leetcode.com/topic/11877/detailed-explanation-and-generalization-of-the-bitwise-operation-method-for-single-numbers/2
26+
*/
27+
public int singleNumber(int[] nums) {
28+
int counter1 = 0;
29+
int counter2 = 0;
30+
int mask = 0;
31+
for (int num : nums) {
32+
counter2 ^= counter1 & num;
33+
counter1 ^= num;
34+
mask = ~(counter1 & counter2);
35+
counter1 &= mask;
36+
counter2 &= mask;
37+
}
38+
return counter1;
39+
}
4540
}
46-
}
4741
}

0 commit comments

Comments
 (0)