Lets say I have two arrays of integer and I want to merge them without duplicates.
I know I can add them in Set and then can retrieve them as arraylist.
But without using any built-in function how to do it?
Lets say I have two arrays of integer and I want to merge them without duplicates.
I know I can add them in Set and then can retrieve them as arraylist.
But without using any built-in function how to do it?
Depends on how you want to merge them, since an array has an ordering of its elements.
You can just add one after the other (easiest) or "zip" them (one element from A, then one from B, then another from A, etc).
The main problem is that you have to do a check in your new array whether it already contains a value you're trying to add. This is easiest with built-in functions and implementations, like Set. There are Set implementations, like HashSet, which give you constant-time performance for looking up values and inserting them.
I really advise you to just do it the "usual" way and not try and reinvent the wheel.
I find this quite readable:
static int[] merge(int[] a, int[] b) {
Set<Integer> set = new HashSet<>(Arrays.asList(a));
set.addAll(Arrays.asList(b)); // skips duplicate as per Set implementation
return set.toArray(new int[0]);
}
This uses both duplication and built-in methods, but it's clear and concise.
private Set<Integer> mergeWithoutDuplicates(int[] a, int[] b) {
Set<Integer> set1= new HashSet<Integer>(a.length+b.length);
for (int i=0; i<a.length; i++) {
set1.add(a[i]);
}
for (int i=0; i<b.length; i++) {
set1.add(b[i]);
}
return set1;
}
This function should serve your purpose
A lot of code but here is a sample..
try{
int[] a = {1,2,3,4,5,6,7};
int[] b = {5,6,7,8,9,10};
int[] c = new int[a.length+b.length];
int[] fin = new int[a.length+b.length];
int i = 0;
for(int j : fin){
fin[i++] = -1;
}
i = 0;
for(int j : a){
c[i++] = j;
}
for(int j : b){
c[i++] = j;
}
boolean check = false;
for(int j = 0,k = 0; j < c.length; j++){
for(int l : fin){
if( l == c[j] )
check = true;
}
if(!check){
fin[k++] = c[j];
} else check = false;
}
} catch(Exception ex){
ex.printStackTrace();
}