Skip to content

Commit 3640210

Browse files
refactor 136
1 parent 5ce5865 commit 3640210

File tree

1 file changed

+28
-44
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+28
-44
lines changed

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

Lines changed: 28 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -4,54 +4,38 @@
44
import java.util.Iterator;
55
import java.util.Set;
66

7-
/**136. Single Number
8-
9-
Given a non-empty array of integers, every element appears twice 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-
Example 1:
15-
Input: [2,2,1]
16-
Output: 1
17-
18-
Example 2:
19-
Input: [4,1,2,1,2]
20-
Output: 4
21-
*/
22-
237
public class _136 {
248

25-
public static class Solution1 {
26-
/**
27-
* Approach 1: use set, since this problem explicitly states that every element appears twice
28-
* and only one appears once so, we could safely remove the ones that are already in the set,
29-
* O(n) time and O(n) space. HashTable approach works similarly like this one, but it could be
30-
* more easily extend to follow-up questions.
31-
*/
32-
public int singleNumber(int[] nums) {
33-
Set<Integer> set = new HashSet();
34-
for (int i : nums) {
35-
if (!set.add(i)) {
36-
set.remove(i);
9+
public static class Solution1 {
10+
/**
11+
* Approach 1: use set, since this problem explicitly states that every element appears twice
12+
* and only one appears once so, we could safely remove the ones that are already in the set,
13+
* O(n) time and O(n) space. HashTable approach works similarly like this one, but it could be
14+
* more easily extend to follow-up questions.
15+
*/
16+
public int singleNumber(int[] nums) {
17+
Set<Integer> set = new HashSet();
18+
for (int i : nums) {
19+
if (!set.add(i)) {
20+
set.remove(i);
21+
}
22+
}
23+
return set.iterator().next();
3724
}
38-
}
39-
return set.iterator().next();
4025
}
41-
}
4226

43-
public static class Solution2 {
44-
/**
45-
* Approach 2: bit manipulation, use exclusive or ^ to solve this problem: we're using the trick
46-
* here: every number ^ itself will become zero, so, the only remaining element will be the one
47-
* that appeared only once.
48-
*/
49-
public int singleNumber(int[] nums) {
50-
int res = 0;
51-
for (int i : nums) {
52-
res ^= i;
53-
}
54-
return res;
27+
public static class Solution2 {
28+
/**
29+
* Approach 2: bit manipulation, use exclusive or ^ to solve this problem: we're using the trick
30+
* here: every number ^ itself will become zero, so, the only remaining element will be the one
31+
* that appeared only once.
32+
*/
33+
public int singleNumber(int[] nums) {
34+
int res = 0;
35+
for (int i : nums) {
36+
res ^= i;
37+
}
38+
return res;
39+
}
5540
}
56-
}
5741
}

0 commit comments

Comments
 (0)