📌  相关文章
📜  Java程序从两个排序数组中打印不常见的元素

📅  最后修改于: 2022-05-13 01:55:22.283000             🧑  作者: Mango

Java程序从两个排序数组中打印不常见的元素

给定两个不同元素的排序数组,我们需要打印两个数组中不常见的元素。输出应按排序顺序打印。
例子 :

Input : arr1[] = {10, 20, 30}
        arr2[] = {20, 25, 30, 40, 50}
Output : 10 25 40 50
We do not print 20 and 30 as these
elements are present in both arrays.

Input : arr1[] = {10, 20, 30}
        arr2[] = {40, 50}
Output : 10 20 30 40 50
        

这个想法是基于归并排序的归并过程。我们遍历两个数组并跳过公共元素。

Java
// Java program to find uncommon elements
// of two sorted arrays
import java.io.*;
  
class GFG {
      
    static void printUncommon(int arr1[], 
                     int arr2[], int n1, int n2)
    {
  
        int i = 0, j = 0, k = 0;
        while (i < n1 && j < n2) {
  
            // If not common, print smaller
            if (arr1[i] < arr2[j]) {
                System.out.print(arr1[i] + " ");
                i++;
                k++;
            }
            else if (arr2[j] < arr1[i]) {
                System.out.print(arr2[j] + " ");
                k++;
                j++;
            }
  
            // Skip common element
            else {
                i++;
                j++;
            }
        }
  
        // printing remaining elements
        while (i < n1) {
            System.out.print(arr1[i] + " ");
            i++;
            k++;
        }
        while (j < n2) {
            System.out.print(arr2[j] + " ");
            j++;
            k++;
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr1[] = { 10, 20, 30 };
        int arr2[] = { 20, 25, 30, 40, 50 };
  
        int n1 = arr1.length;
        int n2 = arr2.length;
  
        printUncommon(arr1, arr2, n1, n2);
    }
}
  
// This code is contributed by vt_m


输出 :
10 25 40 50

有关详细信息,请参阅有关从两个排序数组中打印不常见元素的完整文章!