forked from JFulgoni/Java-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleNumber.java
More file actions
60 lines (54 loc) · 1.16 KB
/
Copy pathSingleNumber.java
File metadata and controls
60 lines (54 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package john_test;
import java.util.HashSet;
import java.util.Set;
public class SingleNumber {
public SingleNumber(){
}
public int findSingle(int[] array){
/*
* the best solution for this is to use the ^ symbol to perform a bitwise XOR
* with XOR, if there's ever a number that appears twice, it will cancel out
* that's just a weird trick
*/
// int result = 0;
// for(int a : array){
// result = result ^ a;
// System.out.print(result);
// }
// return result;
Set<Integer> first = new HashSet<Integer>();
//Set<Integer> second = new HashSet<Integer>();
for(int a: array){
if(first.contains(a)){
first.remove(a);
}
else{
first.add(a);
}
}
for(Integer i: first){
return i;
}
return Integer.MAX_VALUE;
}
public int findSingleII(int[] array){
Set<Integer> first = new HashSet<Integer>();
Set<Integer> second = new HashSet<Integer>();
for(int a: array){
if(first.contains(a) && second.contains(a)){
first.remove(a);
second.remove(a);
}
else if(first.contains(a)){
second.add(a);
}
else{
first.add(a);
}
}
for(Integer i: first){
return i;
}
return Integer.MAX_VALUE;
}
}