|
9 | 9 |
|
10 | 10 | Note: |
11 | 11 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? |
12 | | -
|
13 | 12 | */ |
14 | 13 |
|
15 | 14 | public class _136 { |
16 | | - //approach 1: use set, since this problem explicitly states that every element appears twice and only one appears once |
17 | | - //so, we could safely remove the ones that are already in the set, O(n) time and O(n) space. |
18 | | - //HashTable approach works similarly like this one, but it could be more easily extend to follow-up questions. |
19 | | - public int singleNumber_using_set(int[] nums) { |
20 | | - Set<Integer> set = new HashSet(); |
21 | | - for (int i : nums) { |
22 | | - if (!set.add(i)) { |
23 | | - set.remove(i); |
| 15 | + |
| 16 | + public static class Solution1 { |
| 17 | + /**approach 1: use set, since this problem explicitly states that every element appears twice and only one appears once |
| 18 | + so, we could safely remove the ones that are already in the set, O(n) time and O(n) space. |
| 19 | + HashTable approach works similarly like this one, but it could be more easily extend to follow-up questions.*/ |
| 20 | + public int singleNumber(int[] nums) { |
| 21 | + Set<Integer> set = new HashSet(); |
| 22 | + for (int i : nums) { |
| 23 | + if (!set.add(i)) { |
| 24 | + set.remove(i); |
| 25 | + } |
24 | 26 | } |
| 27 | + Iterator<Integer> it = set.iterator(); |
| 28 | + return it.next(); |
25 | 29 | } |
26 | | - Iterator<Integer> it = set.iterator(); |
27 | | - return it.next(); |
28 | 30 | } |
29 | 31 |
|
30 | 32 |
|
31 | | - //approach 2: bit manipulation, use exclusive or ^ to solve this problem: |
32 | | - //we're using the trick here: every number ^ itself will become zero, so, the only remaining element will be the one that |
33 | | - //appeared only once. |
34 | | - public int singleNumber_using_bit(int[] nums) { |
35 | | - int res = 0; |
36 | | - for (int i : nums) { |
37 | | - res ^= i; |
| 33 | + public static class Solution2 { |
| 34 | + /**approach 2: bit manipulation, use exclusive or ^ to solve this problem: |
| 35 | + we're using the trick here: every number ^ itself will become zero, so, the only remaining element will be the one that |
| 36 | + appeared only once.*/ |
| 37 | + public int singleNumber(int[] nums) { |
| 38 | + int res = 0; |
| 39 | + for (int i : nums) { |
| 40 | + res ^= i; |
| 41 | + } |
| 42 | + return res; |
38 | 43 | } |
39 | | - return res; |
40 | 44 | } |
41 | 45 |
|
42 | 46 | } |
0 commit comments