This is the question:
Given 3 random arrays of integers, write a method to find the smallest number that is common among the 3 arrays. HINT: Sort first and just traverse first few elements until you reach the common number
[-1,-2, 4,5,6,1,2,3,3,3,1,1,1]
[54,6,7,8,1,3,5,1]
[1,6,9,1,0,2,1]
result = 1
I wrote a working solution code but I wonder if there is a simpler and more efficient way to do this.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Smcomm {
public static void main(String[] args) {
int[] A = {-1,-2,4,5,6,1,2,3,3,3,1,1,1};
int[] B = {54,6,7,8,1,3,5,1};
int[] C = {1,6,9,1,0,2,1};
ArrayList<Integer> ar1 = new ArrayList<Integer>();
ArrayList<Integer> ar2 = new ArrayList<Integer>();
ArrayList<Integer> ar3 = new ArrayList<Integer>();
for(int el: A){
ar1.add(el);
}
for(int el: B){
ar2.add(el);
}
for(int el: C){
ar3.add(el);
}
Collections.sort(ar1);
Collections.sort(ar2);
Collections.sort(ar3);
printer(ar1);
printer(ar2);
printer(ar3);
finder(ar1,ar2,ar3);
}
static void printer(ArrayList ar){
Iterator<Integer> it = ar.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("--------------------");
}
static void finder(ArrayList ar1, ArrayList ar2, ArrayList ar3){
ar1.retainAll(ar2);
ar1.retainAll(ar3);
if(ar1.size()>0){
System.out.println(ar1.get(1));
}else {
System.out.println("no comm el");
}
}
}
The method that doesn't convice me totally is retainAll because I think have a complexity O(n^2).
I don't need to find all the elements but I want only to find the smallest. Do you know maybe if is possible someway to stop the execution of the method when it find the first element in common in the array? Shouldn't be difficult because the arrays are already sorted.
Thanks for the help.