|
3 | 3 | import java.util.HashMap;
|
4 | 4 | import java.util.Map;
|
5 | 5 |
|
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 |
| -*/ |
14 | 6 | public class _137 {
|
15 | 7 |
|
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; |
25 | 20 | }
|
26 |
| - } |
27 |
| - return 0; |
28 | 21 | }
|
29 |
| - } |
30 | 22 |
|
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 | + } |
45 | 40 | }
|
46 |
| - } |
47 | 41 | }
|
0 commit comments