-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathFind Two Unique Numbers.java
More file actions
56 lines (46 loc) · 1.3 KB
/
Find Two Unique Numbers.java
File metadata and controls
56 lines (46 loc) · 1.3 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
//brute
import java.util.HashMap;
import java.util.Map;
class TwoUniqueHashMap {
public static void findTwoUniques(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
// Count frequency
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
// Print elements with frequency 1
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
System.out.print(entry.getKey() + " ");
}
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 1, 3, 2, 5};
findTwoUniques(arr);
}
}
//optimized
class TwoSingleNumbers {
public static int[] singleNumber(int[] nums) {
int xor = 0;
for (int num : nums) {
xor ^= num;
}
int diffBit = xor & (-xor); // rightmost set bit
int x = 0, y = 0;
for (int num : nums) {
if ((num & diffBit) == 0) {
x ^= num;
} else {
y ^= num;
}
}
return new int[]{x, y};
}
public static void main(String[] args) {
int[] arr = {1, 2, 1, 3, 2, 5};
int[] res = singleNumber(arr);
System.out.println(res[0] + " " + res[1]);
}
}