|
3 | 3 | import java.util.HashMap;
|
4 | 4 | import java.util.Map;
|
5 | 5 |
|
6 |
| -/**137. Single Number II |
| 6 | +/** |
| 7 | + * 137. Single Number II |
| 8 | +
|
7 | 9 | Given an array of integers, every element appears three times except for one. Find that single one.
|
8 | 10 |
|
9 | 11 | Note:
|
10 | 12 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
|
11 |
| -
|
12 | 13 | */
|
13 | 14 | public class _137 {
|
14 | 15 |
|
15 |
| - public static class Solution1 { |
16 |
| - public int singleNumber(int[] nums) { |
17 |
| - Map<Integer, Integer> map = new HashMap(); |
18 |
| - for (int i : nums) { |
19 |
| - map.put(i, map.getOrDefault(i, 0) + 1); |
20 |
| - } |
21 |
| - for (int key : map.keySet()) { |
22 |
| - if (map.get(key) != 3) { |
23 |
| - return key; |
24 |
| - } |
25 |
| - } |
26 |
| - return 0; |
| 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; |
27 | 25 | }
|
| 26 | + } |
| 27 | + return 0; |
28 | 28 | }
|
| 29 | + } |
29 | 30 |
|
30 |
| - public static class Solution2 { |
31 |
| - /**Credit: https://discuss.leetcode.com/topic/11877/detailed-explanation-and-generalization-of-the-bitwise-operation-method-for-single-numbers/2*/ |
32 |
| - public int singleNumber(int[] nums) { |
33 |
| - int counter1 = 0; |
34 |
| - int counter2 = 0; |
35 |
| - int mask = 0; |
36 |
| - for (int num : nums) { |
37 |
| - counter2 ^= counter1 & num; |
38 |
| - counter1 ^= num; |
39 |
| - mask = ~(counter1 & counter2); |
40 |
| - counter1 &= mask; |
41 |
| - counter2 &= mask; |
42 |
| - } |
43 |
| - return counter1; |
44 |
| - } |
| 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; |
45 | 45 | }
|
46 |
| - |
| 46 | + } |
47 | 47 | }
|
0 commit comments