Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created September 9, 2016 19:54
Show Gist options
  • Save nichtemna/08a98d6a5d5f6de61211e51a584d3d72 to your computer and use it in GitHub Desktop.
Save nichtemna/08a98d6a5d5f6de61211e51a584d3d72 to your computer and use it in GitHub Desktop.
Find interception of three array
import java.util.*;
/**
* Given a 3 array like below
NSArray *a = [1,3,4,5];
NSArray *b = [-1,3,0,9];
NSArray *c = [0,31,32,22,6];
Find the elements from the three array which existing in atleast 2 arrays.
Eg: [3, 0]
*/
public class ThreeArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] first = new int[scanner.nextInt()];
int[] second = new int[scanner.nextInt()];
int[] third = new int[scanner.nextInt()];
for (int i = 0; i < first.length; i++) {
first[i] = scanner.nextInt();
}
for (int i = 0; i < second.length; i++) {
second[i] = scanner.nextInt();
}
for (int i = 0; i < third.length; i++) {
third[i] = scanner.nextInt();
}
for (int i : getInterception(first, second, third)) {
System.out.println(i);
}
}
private static List<Integer> getInterception(int[] first, int[] second, int[] third) {
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int i = 0; i < first.length; i++) {
addValueToSet(1, first[i], map);
}
for (int i = 0; i < second.length; i++) {
addValueToSet(2, second[i], map);
}
for (int i = 0; i < third.length; i++) {
addValueToSet(3, third[i], map);
}
List<Integer> list = new ArrayList<>();
for (Integer i : map.keySet()) {
if (map.get(i).size() > 1) {
list.add(i);
}
}
return list;
}
private static void addValueToSet(int key, int value, Map<Integer, Set<Integer>> map) {
Set<Integer> set;
if (map.containsKey(value)) {
set = map.get(value);
} else {
set = new HashSet<>();
}
set.add(key);
map.put(value, set);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment