Given two arrays of ints that are sets, create a function to merge them to create a new set.A set must pass on these three conditions:- All values are positive- Sorted- Non-duplicates
Solution:
import java.util.LinkedHashSet;
import java.util.Set;
public class MergeSortedArrays {
public static void main(String[] args) {
int[] a= {1,2,6,9,10,27};
int[] b= {2,8,10,89};
int[] result=merge(a,b);
Set<Integer> set = new LinkedHashSet<Integer>();
for(int i : result)
{
set.add(i);
}
System.out.println(set);
}
public static int[] merge(int[] a,int[] b)
{
int m=0;int n=0;
int k=a.length+b.length;
int[] c=new int[k];
int j=0;
while(m<a.length && n<b.length)
{
c[j++] = a[m]<=b[n] ? a[m++] :b[n++];
}
while(m<a.length)
{
c[j++]=a[m++];
}
while(n<b.length)
{
c[j++]=b[n++];
}
return c;
}
}
//Result is sorted with no duplicates
[1, 2, 6, 8, 9, 10, 27, 89]
Post a Comment