Skip to content

Commit c5d5a52

Browse files
Single Number
1 parent 9640728 commit c5d5a52

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

MEDIUM/src/medium/SingleNumber.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package medium;
2+
3+
import java.util.HashSet;
4+
import java.util.Iterator;
5+
import java.util.Set;
6+
7+
/**136. Single Number QuestionEditorial Solution My Submissions
8+
Total Accepted: 141879
9+
Total Submissions: 277792
10+
Difficulty: Medium
11+
Given an array of integers, every element appears twice except for one. Find that single one.
12+
13+
Note:
14+
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
15+
16+
Hide Company Tags Palantir Airbnb
17+
Hide Tags Hash Table Bit Manipulation
18+
Hide Similar Problems (M) Single Number II (M) Single Number III (M) Missing Number (H) Find the Duplicate Number
19+
*/
20+
public class SingleNumber {
21+
//approach 1: use set, since this problem explicitly states that every element appears twice and only one appears once
22+
//so, we could safely remove the ones that are already in the set, O(n) time and O(n) space.
23+
//HashTable approach works similarly like this one, but it could be more easily extend to follow-up questions.
24+
public int singleNumber_using_set(int[] nums) {
25+
Set<Integer> set = new HashSet();
26+
for(int i : nums){
27+
if(!set.add(i)) set.remove(i);
28+
}
29+
Iterator<Integer> it = set.iterator();
30+
return it.next();
31+
}
32+
33+
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_using_bit(int[] nums) {
38+
int res = 0;
39+
for(int i : nums){
40+
res ^= i;
41+
}
42+
return res;
43+
}
44+
45+
}

0 commit comments

Comments
 (0)