Skip to content

Instantly share code, notes, and snippets.

@anil477
Created June 13, 2017 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/bb88b5110e1ec602b485dd1123b8e56d to your computer and use it in GitHub Desktop.
Save anil477/bb88b5110e1ec602b485dd1123b8e56d to your computer and use it in GitHub Desktop.
Union and Intersection of sorted array
import java.io.*;
import java.util.*;
class unionIntersection
{
public static void main (String[] args) throws java.lang.Exception
{
unionIntersection obj = new unionIntersection();
obj.approachTwo();
}
public void approachTwo()
{
int[] a = new int[]{1, 3, 5, 6 ,7, 9, 10, 12};
int[] b = new int[]{1, 2, 4, 5, 6};
List<Integer> union = new ArrayList<Integer>();
List<Integer> inter = new ArrayList<Integer>();
int i = 0, j = 0, lengtha = a.length, lengthb = b.length;
while((i < lengtha) && (j < lengthb)) {
if(a[i] == b[j]) {
inter.add(a[i]);
union.add(a[i]);
i++;
j++;
continue;
}
if( a[i] > b[j]) {
union.add(b[j]);
j++;
} else {
union.add(a[i]);
i++;
}
}
while(i < lengtha) {
union.add(a[i]);
i++;
}
while(j < lengthb) {
union.add(b[j]);
j++;
}
System.out.println(" Union ");
for(Integer x: union) {
System.out.println(x);
}
System.out.println(" Intersection ");
for(Integer x: inter) {
System.out.println(x);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment