Created
June 13, 2017 15:39
-
-
Save anil477/bb88b5110e1ec602b485dd1123b8e56d to your computer and use it in GitHub Desktop.
Union and Intersection of sorted array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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