Java程序查找两个数组的并集

Here you will get java program to find union of two arrays.

在这里,您将获得Java 程序来查找两个数组的并集

For example we have two sorted arrays a1[] = {2, 3, 5, 11} and a2[] = {4, 7, 9} then union of a1 and a2 will be {2, 3, 4, 5, 7, 9, 11}. A Java program for finding union of two arrays is given below.

例如,我们有两个已排序的数组a1 [] = {2,3,5,11}和a2 [] = {4,7,9},那么a1和a2的并集将是{2,3,4,5,7 ,9、11}。 下面给出了用于查找两个数组的并集的Java程序。

Also Read: Java Program to Find Smallest and Largest Element in an Array

另请阅读: Java程序,用于查找数组中的最小和最大元素

Java程序查找两个数组的并集 (Java Program to Find Union of two Arrays)

package com;
 
import java.util.Scanner;
 
class UnionOfArrays
{
	public static void main(String...s) {
		int i,j,n1,n2;
		Scanner sc=new Scanner(System.in); //used to read from keyboard
		
		System.out.print("Enter number of elements of first array:");
		n1=sc.nextInt();
		System.out.print("Enter number of elements of second array:");
		n2=sc.nextInt();
		
		int a1[]=new int[n1];
		int a2[]=new int[n2];
		
		System.out.print("\nEnter elements of first array in ascending order:");
		for(i=0;i<n1;++i)
			a1[i]=sc.nextInt();
		
		System.out.print("\nEnter elements of second array in ascending order:");
		for(i=0;i<n2;++i)
			a2[i]=sc.nextInt();
	
		i=j=0;
		System.out.print("\nUnion of Arrays: ");
		while(i<n1&&j<n2)
		{
			if(a1[i]<a2[j])
			{
				System.out.print(a1[i]+" ");
				i++;
			}
			else
				if(a2[j]<a1[i])
				{
					System.out.print(a2[j]+" ");
					j++;
				}
				else
				{
					System.out.print(a1[i]+" ");
					i++;
					j++;
				}
		}
		
		if(i<n1)
			while(i<n1)
			{
				System.out.print(a1[i]+" ");
				i++;
			}
		
		if(j<n2)
			while(j<n2)
			{
				System.out.print(a2[j]+" ");
				j++;
			}
	}
}

Output

输出量

Enter number of elements of first array:3 Enter number of elements of second array:5

输入第一个数组 的元素数 :3 输入第二个数组的元素数:5

Enter elements of first array in ascending order:2 4 6

以升序输入第一个数组的元素:2 4 6

Enter elements of second array in ascending order:1 3 7 9 12

以升序输入第二个数组的元素:1 3 7 9 12

Union of Arrays: 1 2 3 4 6 7 9 12

数组联合:1 2 3 4 6 7 9 12

翻译自: https://www.thecrazyprogrammer.com/2014/07/java-program-to-find-union-of-two-arrays.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值