-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommonElementsInArrays.java
73 lines (63 loc) · 2.48 KB
/
CommonElementsInArrays.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
64
65
66
67
68
69
70
71
72
73
package com.java.scaler.hashing;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class CommonElementsInArrays {
int commonElementsIndex = 0;
public static void main(String[] args) {
int[] input1 = { 2, 1, 4, 10};
int[] input2 = {3, 6, 2, 10, 10};
int[] result = new CommonElementsInArrays().findCommonElements(input1, input2);
System.out.println(Arrays.toString(result));
}
private int[] findCommonElements(int[]A, int[]B){
int[] commonElements = new int[A.length];
Map<Integer, Integer> mapOfA = new HashMap<>();
Map<Integer, Integer> mapOfB = new HashMap<>();
for(int i=0; i<A.length; i++){
if(mapOfA.containsKey(A[i])){
mapOfA.put(A[i], mapOfA.get(A[i])+1);
}
else{
mapOfA.put(A[i], 1);
}
}
for(int i=0; i<B.length; i++){
if(mapOfB.containsKey(B[i])){
mapOfB.put(B[i], mapOfB.get(B[i])+1);
}
else{
mapOfB.put(B[i], 1);
}
}
int compareCount = mapOfA.size()<mapOfB.size() ? mapOfA.size() : mapOfB.size();
char compareArray = mapOfA.size()<mapOfB.size() ? 'A' : 'B';
if(compareArray=='A'){
for(Integer key : mapOfA.keySet()){
if(mapOfB.containsKey(key)){
int keyCount = mapOfA.get(key) < mapOfB.get(key) ? mapOfA.get(key) : mapOfB.get(key);
for (int y = 0; y < keyCount; y++) {
commonElements[commonElementsIndex] = key;
commonElementsIndex++;
}
}
}
}
else if(compareArray=='B'){
for(Integer key : mapOfB.keySet()) {
if (mapOfA.containsKey(key)) {
int keyCount = mapOfA.get(key) < mapOfB.get(key) ? mapOfA.get(key) : mapOfB.get(key);
for (int y = 0; y < keyCount; y++) {
commonElements[commonElementsIndex] = key;
commonElementsIndex++;
}
}
}
}
int[] returnArray = new int[commonElementsIndex];
for(int q=0; q<commonElementsIndex; q++){
returnArray[q] = commonElements[q];
}
return returnArray;
}
}