-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberAppearOnce.java
63 lines (61 loc) · 1.76 KB
/
NumberAppearOnce.java
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
61
62
63
import java.util.HashMap;
import java.util.Map;
public class NumberAppearOnce {
public static int bruteapproach(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int num = arr[i];
int cnt = 0;
for (int j = 0; j < arr.length; j++) {
if (num == arr[j]) {
cnt++;
}
}
if (cnt == 1) {
return num;
}
}
return -1;
}
public static int better1(int[] arr) { // IMPLEMENTING HASHMAP USING ARRAY DS
int maxi = arr[0];
for (int i = 1; i < arr.length; i++) {
if (maxi < arr[i]) {
maxi = arr[i];
}
}
int []hash = new int[maxi+1];
for (int i = 0; i < arr.length; i++) {
hash[arr[i]]++;
}
for (int i = 0; i < arr.length; i++) {
if (hash[arr[i]] == 1) {
return arr[i];
}
}
return -1;
}
public static int better2(int[] arr) { //IMPLEMENTING HASHMAP USING MAP DS
HashMap<Integer, Integer> mpp = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int value = mpp.getOrDefault(arr[i], 0);
mpp.put(arr[i], value + 1);
}
for (Map.Entry<Integer, Integer> it : mpp.entrySet()) {
if (it.getValue() == 1) {
return it.getKey();
}
}
return -1;
}
public static int optimal(int[] arr) {
int xor = 0;
for (int i = 0; i < arr.length; i++) {
xor ^= arr[i];
}
return xor;
}
public static void main(String[] args) {
int[] arr = {1,1,2,2,3,4,4,5,6,5,6,8,8};
System.out.println(optimal(arr));
}
}