Union of two sorted arrays code in java
import java.util.*;
public class MyFirstClass {
public static void main(String[] args) {
int arr1[] = {1,1,2,3,4,5};
int arr2[] = {2,3,4,4,5,10,20,100};
int n1 = arr1.length; int n2=arr2.length;
int leng = n1+n2;
int i=0;int j=0;
ArrayList<Integer> Union = new ArrayList<>();
while(i<n1 && j<n2)
{
if (arr1[i] <= arr2[j]) // Case 1 and 2
{
if (Union.size() == 0 || Union.get(Union.size()-1) != arr1[i])
Union.add(arr1[i]);
i++;
} else // case 3
{
if (Union.size() == 0 || Union.get(Union.size()-1) != arr2[j])
Union.add(arr2[j]);
j++;
}
}
while(j<n2)
{
if (Union.size() == 0 || Union.get(Union.size()-1) != arr2[j])
Union.add(arr2[j]);
j++;
}
while(i<n1)
{
if (Union.size() == 0 || Union.get(Union.size()-1) != arr1[i])
Union.add(arr1[i]);
i++;
}
System.out.println(Union);
}
}
No comments:
Post a Comment