📜  两个排序数组的并集和交集

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

两个排序数组的并集和交集

给定两个排序数组,找到它们的并集和交集。

例子:

Input : arr1[] = {1, 3, 4, 5, 7}
        arr2[] = {2, 3, 5, 6} 
Output : Union : {1, 2, 3, 4, 5, 6, 7} 
         Intersection : {3, 5}

Input : arr1[] = {2, 5, 6}
        arr2[] = {4, 6, 8, 10} 
Output : Union : {2, 4, 5, 6, 8, 10} 
         Intersection : {6}

我们强烈建议您单击此处并进行练习,然后再继续使用解决方案。

数组 arr1[] 和 arr2[] 的并集

要查找两个排序数组的并集,请遵循以下合并过程:

以下是上述方法的实现:

C++
// C++ program to find union of
// two sorted arrays
#include 
using namespace std;
 
/* Function prints union of arr1[] and arr2[]
   m is the number of elements in arr1[]
   n is the number of elements in arr2[] */
void printUnion(int arr1[], int arr2[], int m, int n)
{
    int i = 0, j = 0;
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            cout << arr1[i++] << " ";
 
        else if (arr2[j] < arr1[i])
            cout << arr2[j++] << " ";
 
        else {
            cout << arr2[j++] << " ";
            i++;
        }
    }
 
    /* Print remaining elements of the larger array */
    while (i < m)
        cout << arr1[i++] << " ";
 
    while (j < n)
        cout << arr2[j++] << " ";
}
 
/* Driver program to test above function */
int main()
{
    int arr1[] = { 1, 2, 4, 5, 6 };
    int arr2[] = { 2, 3, 5, 7 };
 
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function calling
    printUnion(arr1, arr2, m, n);
 
    return 0;
}


C
// C program to find union of
// two sorted arrays
#include 
 
/* Function prints union of arr1[] and arr2[]
   m is the number of elements in arr1[]
   n is the number of elements in arr2[] */
void printUnion(int arr1[], int arr2[], int m, int n)
{
    int i = 0, j = 0;
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            printf(" %d ", arr1[i++]);
        else if (arr2[j] < arr1[i])
            printf(" %d ", arr2[j++]);
        else {
            printf(" %d ", arr2[j++]);
            i++;
        }
    }
 
    /* Print remaining elements of the larger array */
    while (i < m)
        printf(" %d ", arr1[i++]);
    while (j < n)
        printf(" %d ", arr2[j++]);
}
 
/* Driver program to test above function */
int main()
{
    int arr1[] = { 1, 2, 4, 5, 6 };
    int arr2[] = { 2, 3, 5, 7 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
    printUnion(arr1, arr2, m, n);
    getchar();
    return 0;
}


Java
// Java program to find union of
// two sorted arrays
 
class FindUnion {
    /* Function prints union of arr1[] and arr2[]
    m is the number of elements in arr1[]
    n is the number of elements in arr2[] */
    static int printUnion(int arr1[], int arr2[], int m, int n)
    {
        int i = 0, j = 0;
        while (i < m && j < n) {
            if (arr1[i] < arr2[j])
                System.out.print(arr1[i++] + " ");
            else if (arr2[j] < arr1[i])
                System.out.print(arr2[j++] + " ");
            else {
                System.out.print(arr2[j++] + " ");
                i++;
            }
        }
 
        /* Print remaining elements of
         the larger array */
        while (i < m)
            System.out.print(arr1[i++] + " ");
        while (j < n)
            System.out.print(arr2[j++] + " ");
 
        return 0;
    }
 
    public static void main(String args[])
    {
        int arr1[] = { 1, 2, 4, 5, 6 };
        int arr2[] = { 2, 3, 5, 7 };
        int m = arr1.length;
        int n = arr2.length;
        printUnion(arr1, arr2, m, n);
    }
}


Python3
# Python program to find union of
# two sorted arrays
# Function prints union of arr1[] and arr2[]
# m is the number of elements in arr1[]
# n is the number of elements in arr2[]
def printUnion(arr1, arr2, m, n):
    i, j = 0, 0
    while i < m and j < n:
        if arr1[i] < arr2[j]:
            print(arr1[i],end=" ")
            i += 1
        elif arr2[j] < arr1[i]:
            print(arr2[j],end=" ")
            j+= 1
        else:
            print(arr2[j],end=" ")
            j += 1
            i += 1
 
    # Print remaining elements of the larger array
    while i < m:
        print(arr1[i],end=" ")
        i += 1
 
    while j < n:
        print(arr2[j],end=" ")
        j += 1
 
# Driver program to test above function
arr1 = [1, 2, 4, 5, 6]
arr2 = [2, 3, 5, 7]
m = len(arr1)
n = len(arr2)
printUnion(arr1, arr2, m, n)
 
# This code is contributed by Pratik Chhajer


C#
// C# program to find union of
// two sorted arrays
 
using System;
 
class GFG {
    /* Function prints union of arr1[] and arr2[]
    m is the number of elements in arr1[]
    n is the number of elements in arr2[] */
    static int printUnion(int[] arr1,
                          int[] arr2, int m, int n)
    {
        int i = 0, j = 0;
 
        while (i < m && j < n) {
            if (arr1[i] < arr2[j])
                Console.Write(arr1[i++] + " ");
            else if (arr2[j] < arr1[i])
                Console.Write(arr2[j++] + " ");
            else {
                Console.Write(arr2[j++] + " ");
                i++;
            }
        }
 
        /* Print remaining elements of
        the larger array */
        while (i < m)
            Console.Write(arr1[i++] + " ");
        while (j < n)
            Console.Write(arr2[j++] + " ");
 
        return 0;
    }
 
    public static void Main()
    {
        int[] arr1 = { 1, 2, 4, 5, 6 };
        int[] arr2 = { 2, 3, 5, 7 };
        int m = arr1.Length;
        int n = arr2.Length;
 
        printUnion(arr1, arr2, m, n);
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
    static void UnionArray(int arr1[],
                           int arr2[], int l1, int l2)
    {
        // Taking max element present in either array
        int m = arr1[l1 - 1];
        int n = arr2[l2 - 1];
 
        int ans = 0;
 
        if (m > n) {
            ans = m;
        }
        else
            ans = n;
 
        // Finding elements from 1st array
        // (non duplicates only). Using
        // another array for storing union
        // elements of both arrays
        // Assuming max element present
        // in array is not more than 10^7
        int newtable[ans + 1];
        memset(newtable,0,sizeof(newtable));
        // First element is always
        // present in final answer
        cout << arr1[0] << " ";
 
        // Incrementing the First element's count
        // in it's corresponding index in newtable
        ++newtable[arr1[0]];
 
        // Starting traversing the first
        // array from 1st index till last
        for (int i = 1; i < l1; i++) {
            // Checking whether current element
            // is not equal to it's previous element
            if (arr1[i] != arr1[i - 1]) {
                cout << arr1[i] << " ";
                ++newtable[arr1[i]];
            }
        }
 
        // Finding only non common
        // elements from 2nd array
        for (int j = 0; j < l2; j++) {
            // By checking whether it's already
            // present in newtable or not
            if (newtable[arr2[j]] == 0) {
                cout << arr2[j] << " ";
                ++newtable[arr2[j]];
            }
        }
    }
 
// Driver Code
int main()
{
    int arr1[] = { 1, 2, 2, 2, 3 };
    int arr2[] = { 2, 3, 4, 5 };
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int m = sizeof(arr2) / sizeof(arr2[0]);
 
    UnionArray(arr1, arr2, n, m);
 
    return 0;
}
 
// This code is contributed by splevel62.


Java
// Java program to find union of two
// sorted arrays (Handling Duplicates)
class FindUnion {
 
    static void UnionArray(int arr1[],
                           int arr2[])
    {
        // Taking max element present in either array
        int m = arr1[arr1.length - 1];
        int n = arr2[arr2.length - 1];
 
        int ans = 0;
 
        if (m > n) {
            ans = m;
        }
        else
            ans = n;
 
        // Finding elements from 1st array
        // (non duplicates only). Using
        // another array for storing union
        // elements of both arrays
        // Assuming max element present
        // in array is not more than 10^7
        int newtable[] = new int[ans + 1];
 
        // First element is always
        // present in final answer
        System.out.print(arr1[0] + " ");
 
        // Incrementing the First element's count
        // in it's corresponding index in newtable
        ++newtable[arr1[0]];
 
        // Starting traversing the first
        // array from 1st index till last
        for (int i = 1; i < arr1.length; i++) {
            // Checking whether current element
            // is not equal to it's previous element
            if (arr1[i] != arr1[i - 1]) {
                System.out.print(arr1[i] + " ");
                ++newtable[arr1[i]];
            }
        }
 
        // Finding only non common
        // elements from 2nd array
        for (int j = 0; j < arr2.length; j++) {
            // By checking whether it's already
            // present in newtable or not
            if (newtable[arr2[j]] == 0) {
                System.out.print(arr2[j] + " ");
                ++newtable[arr2[j]];
            }
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr1[] = { 1, 2, 2, 2, 3 };
        int arr2[] = { 2, 3, 4, 5 };
 
        UnionArray(arr1, arr2);
    }
}


Python3
# Python3 program to find union of two
# sorted arrays (Handling Duplicates)
def union_array(arr1, arr2):
    m = len(arr1)
    n = len(arr2)
    i = 0
    j = 0
     
    # keep track of last element to avoid duplicates
    prev = None
     
    while i < m and j < n:
        if arr1[i] < arr2[j]:
            if arr1[i] != prev:
                print(arr1[i], end=' ')
                prev = arr1[i]
            i += 1
        elif arr1[i] > arr2[j]:
            if arr2[j] != prev:
                print(arr2[j], end=' ')
                prev = arr2[j]
            j += 1
        else:
            if arr1[i] != prev:
                print(arr1[i], end=' ')
                prev = arr1[i]
            i += 1
            j += 1
             
    while i < m:
        if arr1[i] != prev:
            print(arr1[i], end=' ')
            prev = arr1[i]
        i += 1
 
    while j < n:
        if arr2[j] != prev:
            print(arr2[j], end=' ')
            prev = arr2[j]
        j += 1
     
# Driver Code
if __name__ == "__main__":
    arr1 = [1, 2, 2, 2, 3]
    arr2 = [2, 3, 4, 5]
         
    union_array(arr1, arr2)
 
# This code is contributed by Sanjay Kumar


C#
// C# program to find union of two
// sorted arrays (Handling Duplicates)
using System;
 
class GFG {
 
    static void UnionArray(int[] arr1,
                           int[] arr2)
    {
 
        // Taking max element present
        // in either array
        int m = arr1[arr1.Length - 1];
        int n = arr2[arr2.Length - 1];
 
        int ans = 0;
 
        if (m > n)
            ans = m;
        else
            ans = n;
 
        // Finding elements from 1st array
        // (non duplicates only). Using
        // another array for storing union
        // elements of both arrays
        // Assuming max element present
        // in array is not more than 10^7
        int[] newtable = new int[ans + 1];
 
        // First element is always
        // present in final answer
        Console.Write(arr1[0] + " ");
 
        // Incrementing the First element's
        // count in it's corresponding
        // index in newtable
        ++newtable[arr1[0]];
 
        // Starting traversing the first
        // array from 1st index till last
        for (int i = 1; i < arr1.Length; i++) {
            // Checking whether current
            // element is not equal to
            // it's previous element
            if (arr1[i] != arr1[i - 1]) {
                Console.Write(arr1[i] + " ");
                ++newtable[arr1[i]];
            }
        }
 
        // Finding only non common
        // elements from 2nd array
        for (int j = 0; j < arr2.Length; j++) {
            // By checking whether it's already
            // present in newtable or not
            if (newtable[arr2[j]] == 0) {
                Console.Write(arr2[j] + " ");
                ++newtable[arr2[j]];
            }
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr1 = { 1, 2, 2, 2, 3 };
        int[] arr2 = { 2, 3, 4, 5 };
 
        UnionArray(arr1, arr2);
    }
}
 
// This code is contributed by anuj_67.


Javascript


C++
// This implementation uses vectors but can be easily modified to adapt arrays
#include 
using namespace std;
 
/* Helper function for printUnion().
   This same function can also be implemented as a lambda function inside printUnion().
*/
void next_distinct(const vector &arr, int &x) // Moving to next distinct element
{
  // vector CAN be passed by reference to avoid unnecessary copies.
  // x(index) MUST be passed by reference so to reflect the change in the original index parameter
   
  /* Checks whether the previous element is equal to the current element,
       if true move to the element at the next index else return with the current index
  */
    do
    {
        ++x;
    } while (x < arr.size() && arr[x - 1] == arr[x]);
}
 
void printUnion(vector arr1, vector arr2)
{
    int i = 0, j = 0;
    while (i < arr1.size() && j < arr2.size())
    {
        if (arr1[i] < arr2[j])
        {
            cout << arr1[i] << " ";
            next_distinct(arr1, i); // Incrementing i to next distinct element
        }
        else if (arr1[i] > arr2[j])
        {
            cout << arr2[j] << " ";
            next_distinct(arr2, j); // Incrementing j to next distinct element
        }
        else
        {
            cout << arr1[i] << " ";
            // OR cout << arr2[j] << " ";
            next_distinct(arr1, i); // Incrementing i to next distinct element
            next_distinct(arr2, j); // Incrementing j to next distinct element
        }
    }
    // Remaining elements of the larger array
    while (i < arr1.size())
    {
        cout << arr1[i] << " ";
        next_distinct(arr1, i); // Incrementing i to next distinct element
    }
    while (j < arr2.size())
    {
        cout << arr2[j] << " ";
        next_distinct(arr2, j); // Incrementing j to next distinct element
    }
}
 
int main()
{
    vector arr1 = {1, 2, 2, 2, 3};    // Duplicates Present
    vector arr2 = {2, 3, 3, 4, 5, 5}; // Duplicates Present
 
    printUnion(arr1, arr2);
 
    return 0;
}
// This code is contributed by ciphersaini.


C++
// C++ program to find intersection of
// two sorted arrays
#include 
using namespace std;
 
/* Function prints Intersection of arr1[] and arr2[]
m is the number of elements in arr1[]
n is the number of elements in arr2[] */
void printIntersection(int arr1[], int arr2[], int m, int n)
{
    int i = 0, j = 0;
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            i++;
        else if (arr2[j] < arr1[i])
            j++;
        else /* if arr1[i] == arr2[j] */
        {
            cout << arr2[j] << " ";
            i++;
            j++;
        }
    }
}
 
/* Driver program to test above function */
int main()
{
    int arr1[] = { 1, 2, 4, 5, 6 };
    int arr2[] = { 2, 3, 5, 7 };
 
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function calling
    printIntersection(arr1, arr2, m, n);
 
    return 0;
}


C
// C program to find intersection of
// two sorted arrays
#include 
 
/* Function prints Intersection of arr1[] and arr2[]
   m is the number of elements in arr1[]
   n is the number of elements in arr2[] */
void printIntersection(int arr1[], int arr2[], int m, int n)
{
    int i = 0, j = 0;
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            i++;
        else if (arr2[j] < arr1[i])
            j++;
        else /* if arr1[i] == arr2[j] */
        {
            printf(" %d ", arr2[j++]);
            i++;
        }
    }
}
 
/* Driver program to test above function */
int main()
{
    int arr1[] = { 1, 2, 4, 5, 6 };
    int arr2[] = { 2, 3, 5, 7 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
    printIntersection(arr1, arr2, m, n);
    getchar();
    return 0;
}


Java
// Java program to find intersection of
// two sorted arrays
 
class FindIntersection {
    /* Function prints Intersection of arr1[] and arr2[]
       m is the number of elements in arr1[]
       n is the number of elements in arr2[] */
    static void printIntersection(int arr1[], int arr2[], int m, int n)
    {
        int i = 0, j = 0;
        while (i < m && j < n) {
            if (arr1[i] < arr2[j])
                i++;
            else if (arr2[j] < arr1[i])
                j++;
            else {
                System.out.print(arr2[j++] + " ");
                i++;
            }
        }
    }
 
    public static void main(String args[])
    {
        int arr1[] = { 1, 2, 4, 5, 6 };
        int arr2[] = { 2, 3, 5, 7 };
        int m = arr1.length;
        int n = arr2.length;
        printIntersection(arr1, arr2, m, n);
    }
}


Python3
# Python program to find intersection of
# two sorted arrays
# Function prints Intersection of arr1[] and arr2[]
# m is the number of elements in arr1[]
# n is the number of elements in arr2[]
def printIntersection(arr1, arr2, m, n):
    i, j = 0, 0
    while i < m and j < n:
        if arr1[i] < arr2[j]:
            i += 1
        elif arr2[j] < arr1[i]:
            j+= 1
        else:
            print(arr2[j],end=" ")
            j += 1
            i += 1
 
# Driver program to test above function
arr1 = [1, 2, 4, 5, 6]
arr2 = [2, 3, 5, 7]
m = len(arr1)
n = len(arr2)
printIntersection(arr1, arr2, m, n)
 
# This code is contributed by Pratik Chhajer


C#
// C# program to find Intersection of
// two sorted arrays
 
using System;
 
class GFG {
 
    /* Function prints Intersection of arr1[]
    and arr2[] m is the number of elements in arr1[]
    n is the number of elements in arr2[] */
    static void printIntersection(int[] arr1,
                                  int[] arr2, int m, int n)
    {
        int i = 0, j = 0;
 
        while (i < m && j < n) {
            if (arr1[i] < arr2[j])
                i++;
            else if (arr2[j] < arr1[i])
                j++;
            else {
                Console.Write(arr2[j++] + " ");
                i++;
            }
        }
    }
 
    // driver code
    public static void Main()
    {
        int[] arr1 = { 1, 2, 4, 5, 6 };
        int[] arr2 = { 2, 3, 5, 7 };
        int m = arr1.Length;
        int n = arr2.Length;
 
        printIntersection(arr1, arr2, m, n);
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


Python3
# Python3 program to find Intersection of two
# Sorted Arrays (Handling Duplicates)
def IntersectionArray(a, b, n, m):
    '''
    :param a: given sorted array a
    :param n: size of sorted array a
    :param b: given sorted array b
    :param m: size of sorted array b
    :return: array of intersection of two array or -1
    '''
 
    Intersection = []
    i = j = 0
     
    while i < n and j < m:
        if a[i] == b[j]:
 
            # If duplicate already present in Intersection list
            if len(Intersection) > 0 and Intersection[-1] == a[i]:
                i+= 1
                j+= 1
 
            # If no duplicate is present in Intersection list
            else:
                Intersection.append(a[i])
                i+= 1
                j+= 1
        elif a[i] < b[j]:
            i+= 1
        else:
            j+= 1
             
    if not len(Intersection):
        return [-1]
    return Intersection
 
# Driver Code
if __name__ == "__main__":
 
    arr1 = [1, 2, 2, 3, 4]
    arr2 = [2, 2, 4, 6, 7, 8]
     
    l = IntersectionArray(arr1, arr2, len(arr1), len(arr2))
    print(*l)
 
# This code is contributed by Abhishek Kumar


Javascript


输出:

1 2 3 4 5 6 7 

时间复杂度: O(m + n)

处理任何数组中的重复项:上面的代码不处理任何数组中的重复项。要处理重复项,只需检查每个元素是否相邻元素相等。

下面是这种方法的实现。

C++

// C++ program for the above approach
#include 
using namespace std;
 
    static void UnionArray(int arr1[],
                           int arr2[], int l1, int l2)
    {
        // Taking max element present in either array
        int m = arr1[l1 - 1];
        int n = arr2[l2 - 1];
 
        int ans = 0;
 
        if (m > n) {
            ans = m;
        }
        else
            ans = n;
 
        // Finding elements from 1st array
        // (non duplicates only). Using
        // another array for storing union
        // elements of both arrays
        // Assuming max element present
        // in array is not more than 10^7
        int newtable[ans + 1];
        memset(newtable,0,sizeof(newtable));
        // First element is always
        // present in final answer
        cout << arr1[0] << " ";
 
        // Incrementing the First element's count
        // in it's corresponding index in newtable
        ++newtable[arr1[0]];
 
        // Starting traversing the first
        // array from 1st index till last
        for (int i = 1; i < l1; i++) {
            // Checking whether current element
            // is not equal to it's previous element
            if (arr1[i] != arr1[i - 1]) {
                cout << arr1[i] << " ";
                ++newtable[arr1[i]];
            }
        }
 
        // Finding only non common
        // elements from 2nd array
        for (int j = 0; j < l2; j++) {
            // By checking whether it's already
            // present in newtable or not
            if (newtable[arr2[j]] == 0) {
                cout << arr2[j] << " ";
                ++newtable[arr2[j]];
            }
        }
    }
 
// Driver Code
int main()
{
    int arr1[] = { 1, 2, 2, 2, 3 };
    int arr2[] = { 2, 3, 4, 5 };
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int m = sizeof(arr2) / sizeof(arr2[0]);
 
    UnionArray(arr1, arr2, n, m);
 
    return 0;
}
 
// This code is contributed by splevel62.

Java

// Java program to find union of two
// sorted arrays (Handling Duplicates)
class FindUnion {
 
    static void UnionArray(int arr1[],
                           int arr2[])
    {
        // Taking max element present in either array
        int m = arr1[arr1.length - 1];
        int n = arr2[arr2.length - 1];
 
        int ans = 0;
 
        if (m > n) {
            ans = m;
        }
        else
            ans = n;
 
        // Finding elements from 1st array
        // (non duplicates only). Using
        // another array for storing union
        // elements of both arrays
        // Assuming max element present
        // in array is not more than 10^7
        int newtable[] = new int[ans + 1];
 
        // First element is always
        // present in final answer
        System.out.print(arr1[0] + " ");
 
        // Incrementing the First element's count
        // in it's corresponding index in newtable
        ++newtable[arr1[0]];
 
        // Starting traversing the first
        // array from 1st index till last
        for (int i = 1; i < arr1.length; i++) {
            // Checking whether current element
            // is not equal to it's previous element
            if (arr1[i] != arr1[i - 1]) {
                System.out.print(arr1[i] + " ");
                ++newtable[arr1[i]];
            }
        }
 
        // Finding only non common
        // elements from 2nd array
        for (int j = 0; j < arr2.length; j++) {
            // By checking whether it's already
            // present in newtable or not
            if (newtable[arr2[j]] == 0) {
                System.out.print(arr2[j] + " ");
                ++newtable[arr2[j]];
            }
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr1[] = { 1, 2, 2, 2, 3 };
        int arr2[] = { 2, 3, 4, 5 };
 
        UnionArray(arr1, arr2);
    }
}

Python3

# Python3 program to find union of two
# sorted arrays (Handling Duplicates)
def union_array(arr1, arr2):
    m = len(arr1)
    n = len(arr2)
    i = 0
    j = 0
     
    # keep track of last element to avoid duplicates
    prev = None
     
    while i < m and j < n:
        if arr1[i] < arr2[j]:
            if arr1[i] != prev:
                print(arr1[i], end=' ')
                prev = arr1[i]
            i += 1
        elif arr1[i] > arr2[j]:
            if arr2[j] != prev:
                print(arr2[j], end=' ')
                prev = arr2[j]
            j += 1
        else:
            if arr1[i] != prev:
                print(arr1[i], end=' ')
                prev = arr1[i]
            i += 1
            j += 1
             
    while i < m:
        if arr1[i] != prev:
            print(arr1[i], end=' ')
            prev = arr1[i]
        i += 1
 
    while j < n:
        if arr2[j] != prev:
            print(arr2[j], end=' ')
            prev = arr2[j]
        j += 1
     
# Driver Code
if __name__ == "__main__":
    arr1 = [1, 2, 2, 2, 3]
    arr2 = [2, 3, 4, 5]
         
    union_array(arr1, arr2)
 
# This code is contributed by Sanjay Kumar

C#

// C# program to find union of two
// sorted arrays (Handling Duplicates)
using System;
 
class GFG {
 
    static void UnionArray(int[] arr1,
                           int[] arr2)
    {
 
        // Taking max element present
        // in either array
        int m = arr1[arr1.Length - 1];
        int n = arr2[arr2.Length - 1];
 
        int ans = 0;
 
        if (m > n)
            ans = m;
        else
            ans = n;
 
        // Finding elements from 1st array
        // (non duplicates only). Using
        // another array for storing union
        // elements of both arrays
        // Assuming max element present
        // in array is not more than 10^7
        int[] newtable = new int[ans + 1];
 
        // First element is always
        // present in final answer
        Console.Write(arr1[0] + " ");
 
        // Incrementing the First element's
        // count in it's corresponding
        // index in newtable
        ++newtable[arr1[0]];
 
        // Starting traversing the first
        // array from 1st index till last
        for (int i = 1; i < arr1.Length; i++) {
            // Checking whether current
            // element is not equal to
            // it's previous element
            if (arr1[i] != arr1[i - 1]) {
                Console.Write(arr1[i] + " ");
                ++newtable[arr1[i]];
            }
        }
 
        // Finding only non common
        // elements from 2nd array
        for (int j = 0; j < arr2.Length; j++) {
            // By checking whether it's already
            // present in newtable or not
            if (newtable[arr2[j]] == 0) {
                Console.Write(arr2[j] + " ");
                ++newtable[arr2[j]];
            }
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr1 = { 1, 2, 2, 2, 3 };
        int[] arr2 = { 2, 3, 4, 5 };
 
        UnionArray(arr1, arr2);
    }
}
 
// This code is contributed by anuj_67.

Javascript


输出
1 2 3 

感谢Sanjay Kumar提出这个解决方案。

另一种优化方法:在上面的代码中,我们通过创建newtable[] 使用了一些额外的辅助空间。我们可以通过在增加ij时检查相邻元素来将空间复杂度降低到常数,以便ij直接移动到下一个不同的元素。我们可以就地执行此操作(即不使用任何额外空间)。

C++

// This implementation uses vectors but can be easily modified to adapt arrays
#include 
using namespace std;
 
/* Helper function for printUnion().
   This same function can also be implemented as a lambda function inside printUnion().
*/
void next_distinct(const vector &arr, int &x) // Moving to next distinct element
{
  // vector CAN be passed by reference to avoid unnecessary copies.
  // x(index) MUST be passed by reference so to reflect the change in the original index parameter
   
  /* Checks whether the previous element is equal to the current element,
       if true move to the element at the next index else return with the current index
  */
    do
    {
        ++x;
    } while (x < arr.size() && arr[x - 1] == arr[x]);
}
 
void printUnion(vector arr1, vector arr2)
{
    int i = 0, j = 0;
    while (i < arr1.size() && j < arr2.size())
    {
        if (arr1[i] < arr2[j])
        {
            cout << arr1[i] << " ";
            next_distinct(arr1, i); // Incrementing i to next distinct element
        }
        else if (arr1[i] > arr2[j])
        {
            cout << arr2[j] << " ";
            next_distinct(arr2, j); // Incrementing j to next distinct element
        }
        else
        {
            cout << arr1[i] << " ";
            // OR cout << arr2[j] << " ";
            next_distinct(arr1, i); // Incrementing i to next distinct element
            next_distinct(arr2, j); // Incrementing j to next distinct element
        }
    }
    // Remaining elements of the larger array
    while (i < arr1.size())
    {
        cout << arr1[i] << " ";
        next_distinct(arr1, i); // Incrementing i to next distinct element
    }
    while (j < arr2.size())
    {
        cout << arr2[j] << " ";
        next_distinct(arr2, j); // Incrementing j to next distinct element
    }
}
 
int main()
{
    vector arr1 = {1, 2, 2, 2, 3};    // Duplicates Present
    vector arr2 = {2, 3, 3, 4, 5, 5}; // Duplicates Present
 
    printUnion(arr1, arr2);
 
    return 0;
}
// This code is contributed by ciphersaini.
输出
1 2 3 4 5 

时间复杂度: O(m+n)    其中m & n是数组的大小。

辅助空间: O(1)

数组 arr1[] 和 arr2[] 的交集

要查找 2 个排序数组的交集,请遵循以下方法:

以下是上述方法的实现:

C++

// C++ program to find intersection of
// two sorted arrays
#include 
using namespace std;
 
/* Function prints Intersection of arr1[] and arr2[]
m is the number of elements in arr1[]
n is the number of elements in arr2[] */
void printIntersection(int arr1[], int arr2[], int m, int n)
{
    int i = 0, j = 0;
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            i++;
        else if (arr2[j] < arr1[i])
            j++;
        else /* if arr1[i] == arr2[j] */
        {
            cout << arr2[j] << " ";
            i++;
            j++;
        }
    }
}
 
/* Driver program to test above function */
int main()
{
    int arr1[] = { 1, 2, 4, 5, 6 };
    int arr2[] = { 2, 3, 5, 7 };
 
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function calling
    printIntersection(arr1, arr2, m, n);
 
    return 0;
}

C

// C program to find intersection of
// two sorted arrays
#include 
 
/* Function prints Intersection of arr1[] and arr2[]
   m is the number of elements in arr1[]
   n is the number of elements in arr2[] */
void printIntersection(int arr1[], int arr2[], int m, int n)
{
    int i = 0, j = 0;
    while (i < m && j < n) {
        if (arr1[i] < arr2[j])
            i++;
        else if (arr2[j] < arr1[i])
            j++;
        else /* if arr1[i] == arr2[j] */
        {
            printf(" %d ", arr2[j++]);
            i++;
        }
    }
}
 
/* Driver program to test above function */
int main()
{
    int arr1[] = { 1, 2, 4, 5, 6 };
    int arr2[] = { 2, 3, 5, 7 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
    printIntersection(arr1, arr2, m, n);
    getchar();
    return 0;
}

Java

// Java program to find intersection of
// two sorted arrays
 
class FindIntersection {
    /* Function prints Intersection of arr1[] and arr2[]
       m is the number of elements in arr1[]
       n is the number of elements in arr2[] */
    static void printIntersection(int arr1[], int arr2[], int m, int n)
    {
        int i = 0, j = 0;
        while (i < m && j < n) {
            if (arr1[i] < arr2[j])
                i++;
            else if (arr2[j] < arr1[i])
                j++;
            else {
                System.out.print(arr2[j++] + " ");
                i++;
            }
        }
    }
 
    public static void main(String args[])
    {
        int arr1[] = { 1, 2, 4, 5, 6 };
        int arr2[] = { 2, 3, 5, 7 };
        int m = arr1.length;
        int n = arr2.length;
        printIntersection(arr1, arr2, m, n);
    }
}

Python3

# Python program to find intersection of
# two sorted arrays
# Function prints Intersection of arr1[] and arr2[]
# m is the number of elements in arr1[]
# n is the number of elements in arr2[]
def printIntersection(arr1, arr2, m, n):
    i, j = 0, 0
    while i < m and j < n:
        if arr1[i] < arr2[j]:
            i += 1
        elif arr2[j] < arr1[i]:
            j+= 1
        else:
            print(arr2[j],end=" ")
            j += 1
            i += 1
 
# Driver program to test above function
arr1 = [1, 2, 4, 5, 6]
arr2 = [2, 3, 5, 7]
m = len(arr1)
n = len(arr2)
printIntersection(arr1, arr2, m, n)
 
# This code is contributed by Pratik Chhajer

C#

// C# program to find Intersection of
// two sorted arrays
 
using System;
 
class GFG {
 
    /* Function prints Intersection of arr1[]
    and arr2[] m is the number of elements in arr1[]
    n is the number of elements in arr2[] */
    static void printIntersection(int[] arr1,
                                  int[] arr2, int m, int n)
    {
        int i = 0, j = 0;
 
        while (i < m && j < n) {
            if (arr1[i] < arr2[j])
                i++;
            else if (arr2[j] < arr1[i])
                j++;
            else {
                Console.Write(arr2[j++] + " ");
                i++;
            }
        }
    }
 
    // driver code
    public static void Main()
    {
        int[] arr1 = { 1, 2, 4, 5, 6 };
        int[] arr2 = { 2, 3, 5, 7 };
        int m = arr1.Length;
        int n = arr2.Length;
 
        printIntersection(arr1, arr2, m, n);
    }
}
 
// This code is contributed by Sam007

PHP


Javascript


输出:

2 5

时间复杂度: O(m + n)

处理数组中的重复项:
上面的代码不处理数组中的重复元素。交叉点不应计算重复元素。要处理重复项,只需检查当前元素是否已存在于交集列表中。下面是这种方法的实现。

Python3

# Python3 program to find Intersection of two
# Sorted Arrays (Handling Duplicates)
def IntersectionArray(a, b, n, m):
    '''
    :param a: given sorted array a
    :param n: size of sorted array a
    :param b: given sorted array b
    :param m: size of sorted array b
    :return: array of intersection of two array or -1
    '''
 
    Intersection = []
    i = j = 0
     
    while i < n and j < m:
        if a[i] == b[j]:
 
            # If duplicate already present in Intersection list
            if len(Intersection) > 0 and Intersection[-1] == a[i]:
                i+= 1
                j+= 1
 
            # If no duplicate is present in Intersection list
            else:
                Intersection.append(a[i])
                i+= 1
                j+= 1
        elif a[i] < b[j]:
            i+= 1
        else:
            j+= 1
             
    if not len(Intersection):
        return [-1]
    return Intersection
 
# Driver Code
if __name__ == "__main__":
 
    arr1 = [1, 2, 2, 3, 4]
    arr2 = [2, 2, 4, 6, 7, 8]
     
    l = IntersectionArray(arr1, arr2, len(arr1), len(arr2))
    print(*l)
 
# This code is contributed by Abhishek Kumar

Javascript


输出:

2 4

时间复杂度: O(m + n)
辅助空间: O(min(m, n))

当两个给定数组的大小差异很大时,另一种方法很有用。
这个想法是遍历较短的数组并对大数组中的短数组的每个元素进行二进制搜索(注意数组是排序的)。该解决方案的时间复杂度为 O(min(mLogn, nLogm))。当较大长度与较小长度的比率大于对数阶时,此解决方案比上述方法效果更好。