File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments