forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UniqueIII.java
54 lines (47 loc) · 1.34 KB
/
UniqueIII.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
import java.util.HashMap;
import java.util.Scanner;
public class UniqueIII {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of elements:");
int size = scanner.nextInt();
int[] arr = new int[size];
System.out.println("Enter array elements:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
scanner.close();
int result = findUnique(arr, size);
if (result == -1) {
System.out.println("No unique number found.");
} else {
System.out.println("Unique number:" + result);
}
}
private static int findUnique(int[] arr, int length) {
HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();
for (int i = 0; i < length; i++) {
if (freq.containsKey(arr[i])) {
freq.put(arr[i], freq.get(arr[i]) + 1);
} else {
freq.put(arr[i], 1);
}
}
for(Integer i : freq.keySet()) {
if (freq.get(i) == 1) {
return i;
}
}
return -1;
}
}
/*
* Enter number of elements:
* 7
* Enter array elements:
* 6 2 5 2 2 6 6
* Unique number:5
*
* Time complexity: O(n)
* Space complexity: O(n)
*/