Given is a list containing all but 2 numbers between 1-20 (randomly ordered).
I need to find those 2 numbers.
This is the (working) program I came up with:
public static void main(String[] args) {
int[] x= {1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
ArrayList al= new ArrayList();
Map map= new HashMap();
for(int i=0;i<x.length;i++)
{
map.put(x[i], x[i]);
}
for(int i=1;i<=20;i++)
{
if(map.get(i)==null)
al.add(i);
}
for(int i=0;i<al.size();i++)
{
System.out.println(al.get(i));
}
}
I would like to know if the program is good from a performance point of view (memory and bigO(n))?
You don’t need a map. Just an additional boolean array with size 20.
Now I will expose a straightforward math solution.
First sum all numbers in the array. For example you have
5, 1, 4for the numbers from1, 2, 3, 4, 5. So2and3are missing. We can find them easily with math.So we know
x + y = 15 - 10 = 5Now we will get a second equation:
So:
=>
x = 2, y = 3 or x = 3, y = 2which is the same.So
x = 2, y = 3