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

📅  最后修改于: 2021-05-07 07:53:05             🧑  作者: Mango

给定两个表示两个集合的未排序数组(每个数组中的元素都不同),找到两个数组的并集和交集。
例如,如果输入数组是:
arr1 [] = {7,1,5,2,3,6}
arr2 [] = {3,8,6,20,7}
然后,您的程序应将Union打印为{1,2,3,5,6,7,8,20},并将Intersection打印为{3,6,7}。请注意,并集和相交的元素可以按任何顺序打印。

方法1(使用地图数据结构)

根据数据结构的知识,我们知道映射仅存储不同的密钥。因此,如果我们插入出现不止一次的任何密钥,则它只会存储一次。想法是将两个数组插入一个公共映射中,然后将存储两个数组的不同元素(两个数组的联合)。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
void printUnion(int* a, int n, int* b, int m)
{
     
    // Defining map container mp
    map mp;
   
    // Inserting array elements in mp
    for (int i = 0; i < n; i++)
        mp.insert({ a[i], i });
   
    for (int i = 0; i < m; i++)
        mp.insert({ b[i], i });
    cout << "The union set of both arrays is :" << endl;
    for (auto itr = mp.begin(); itr != mp.end(); itr++)
        cout << itr->first
             << " "; // mp will contain only distinct
                     // elements from array a and b
}
 
// Driver Code
int main()
{
    int a[7] = { 1, 2, 5, 6, 2, 3, 5 };
    int b[9] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 };
 
    printUnion(a, 7, b, 9);
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
static void printUnion(int[] a, int n,
                       int[] b, int m)
{
    Map mp = new HashMap();
     
    // Inserting array elements in mp
    for(int i = 0; i < n; i++)
    {
        mp.put(a[i], i);
    }
    for(int i = 0; i < m; i++)
    {
        mp.put(b[i], i);
    }
     
    System.out.println("The union set of both arrays is :");
    for(Map.Entry mapElement : mp.entrySet())
    {
        System.out.print(mapElement.getKey() + " ");
         
        // mp will contain only distinct
        // elements from array a and b
    }
}
 
// Driver Code
public static void main (String[] args)
{
    int a[] = { 1, 2, 5, 6, 2, 3, 5 };
    int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 };
     
    printUnion(a, 7, b, 9);
}
}
 
// This code is contributed by avanitrachhadiya2155


C++
// A C++ program to print union and intersection
/// of two unsorted arrays
#include 
#include 
using namespace std;
 
int binarySearch(int arr[], int l, int r, int x);
 
// Prints union of arr1[0..m-1] and arr2[0..n-1]
void printUnion(int arr1[], int arr2[], int m, int n)
{
    // Before finding union, make sure arr1[0..m-1]
    // is smaller
    if (m > n) {
        int* tempp = arr1;
        arr1 = arr2;
        arr2 = tempp;
 
        int temp = m;
        m = n;
        n = temp;
    }
 
    // Now arr1[] is smaller
 
    // Sort the first array and print its elements (these
    // two steps can be swapped as order in output is not
    // important)
    sort(arr1, arr1 + m);
    for (int i = 0; i < m; i++)
        cout << arr1[i] << " ";
 
    // Search every element of bigger array in smaller array
    // and print the element if not found
    for (int i = 0; i < n; i++)
        if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
            cout << arr2[i] << " ";
}
 
// Prints intersection of arr1[0..m-1] and arr2[0..n-1]
void printIntersection(int arr1[], int arr2[], int m, int n)
{
    // Before finding intersection, make sure arr1[0..m-1]
    // is smaller
    if (m > n) {
        int* tempp = arr1;
        arr1 = arr2;
        arr2 = tempp;
 
        int temp = m;
        m = n;
        n = temp;
    }
 
    // Now arr1[] is smaller
 
    // Sort smaller array arr1[0..m-1]
    sort(arr1, arr1 + m);
 
    // Search every element of bigger array in smaller
    // array and print the element if found
    for (int i = 0; i < n; i++)
        if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
            cout << arr2[i] << " ";
}
 
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
    if (r >= l) {
        int mid = l + (r - l) / 2;
 
        // If the element is present at the middle itself
        if (arr[mid] == x)
            return mid;
 
        // If element is smaller than mid, then it can only
        // be presen in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);
 
        // Else the element can only be present in right
        // subarray
        return binarySearch(arr, mid + 1, r, x);
    }
 
    // We reach here when element is not present in array
    return -1;
}
 
/* Driver program to test above function */
int main()
{
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
   
    // Function call
    cout << "Union of two arrays is n";
    printUnion(arr1, arr2, m, n);
    cout << "nIntersection of two arrays is n";
    printIntersection(arr1, arr2, m, n);
    return 0;
}


Java
// A Java program to print union and intersection
/// of two unsorted arrays
import java.util.Arrays;
 
class UnionAndIntersection {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    void printUnion(int arr1[], int arr2[], int m, int n)
    {
        // Before finding union, make sure arr1[0..m-1]
        // is smaller
        if (m > n) {
            int tempp[] = arr1;
            arr1 = arr2;
            arr2 = tempp;
 
            int temp = m;
            m = n;
            n = temp;
        }
 
        // Now arr1[] is smaller
        // Sort the first array and print its elements
        // (these two steps can be swapped as order in
        // output is not important)
        Arrays.sort(arr1);
        for (int i = 0; i < m; i++)
            System.out.print(arr1[i] + " ");
 
        // Search every element of bigger array in smaller
        // array and print the element if not found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
                System.out.print(arr2[i] + " ");
        }
    }
 
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    void printIntersection(int arr1[], int arr2[], int m,
                           int n)
    {
        // Before finding intersection, make sure
        // arr1[0..m-1] is smaller
        if (m > n) {
            int tempp[] = arr1;
            arr1 = arr2;
            arr2 = tempp;
 
            int temp = m;
            m = n;
            n = temp;
        }
 
        // Now arr1[] is smaller
        // Sort smaller array arr1[0..m-1]
        Arrays.sort(arr1);
 
        // Search every element of bigger array in smaller
        // array and print the element if found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
                System.out.print(arr2[i] + " ");
        }
    }
 
    // A recursive binary search function. It returns
    // location of x in given array arr[l..r] is present,
    // otherwise -1
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;
 
            // If the element is present at the middle
            // itself
            if (arr[mid] == x)
                return mid;
 
            // If element is smaller than mid, then it can
            // only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
 
            // Else the element can only be present in right
            // subarray
            return binarySearch(arr, mid + 1, r, x);
        }
 
        // We reach here when element is not present in
        // array
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        UnionAndIntersection u_i
            = new UnionAndIntersection();
        int arr1[] = { 7, 1, 5, 2, 3, 6 };
        int arr2[] = { 3, 8, 6, 20, 7 };
        int m = arr1.length;
        int n = arr2.length;
       
        // Function call
        System.out.println("Union of two arrays is ");
        u_i.printUnion(arr1, arr2, m, n);
        System.out.println("");
        System.out.println(
            "Intersection of two arrays is ");
        u_i.printIntersection(arr1, arr2, m, n);
    }
}


Python3
# A Python3 program to print union and intersection
# of two unsorted arrays
 
# Prints union of arr1[0..m-1] and arr2[0..n-1]
 
 
def printUnion(arr1, arr2, m, n):
 
    # Before finding union, make sure arr1[0..m-1]
    # is smaller
    if (m > n):
        tempp = arr1
        arr1 = arr2
        arr2 = tempp
 
        temp = m
        m = n
        n = temp
 
    # Now arr1[] is smaller
 
    # Sort the first array and print its elements (these two
    # steps can be swapped as order in output is not important)
    arr1.sort()
    for i in range(0, m):
        print(arr1[i], end=" ")
 
    # Search every element of bigger array in smaller array
    # and print the element if not found
    for i in range(0, n):
        if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1):
            print(arr2[i], end=" ")
 
# Prints intersection of arr1[0..m-1] and arr2[0..n-1]
 
 
def printIntersection(arr1, arr2, m, n):
 
    # Before finding intersection, make sure arr1[0..m-1]
    # is smaller
    if (m > n):
        tempp = arr1
        arr1 = arr2
        arr2 = tempp
 
        temp = m
        m = n
        n = temp
 
    # Now arr1[] is smaller
 
    # Sort smaller array arr1[0..m-1]
    arr1.sort()
 
    # Search every element of bigger array in smaller
    # array and print the element if found
    for i in range(0, n):
        if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1):
            print(arr2[i], end=" ")
 
# A recursive binary search function. It returns
# location of x in given array arr[l..r] is present,
# otherwise -1
 
 
def binarySearch(arr, l, r, x):
 
    if (r >= l):
        mid = int(l + (r - l)/2)
 
        # If the element is present at the middle itself
        if (arr[mid] == x):
            return mid
 
        # If element is smaller than mid, then it can only
        # be presen in left subarray
        if (arr[mid] > x):
            return binarySearch(arr, l, mid - 1, x)
 
        # Else the element can only be present in right subarray
        return binarySearch(arr, mid + 1, r, x)
 
    # We reach here when element is not present in array
    return -1
 
 
# Driver code
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
m = len(arr1)
n = len(arr2)
 
# Function call
print("Union of two arrays is ")
printUnion(arr1, arr2, m, n)
print("\nIntersection of two arrays is ")
printIntersection(arr1, arr2, m, n)
 
# This code is contributed by mits


C#
// A C# program to print union and
// intersection of two unsorted arrays
using System;
 
class GFG {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int[] arr1, int[] arr2, int m,
                           int n)
    {
        // Before finding union, make
        // sure arr1[0..m-1] is smaller
        if (m > n) {
            int[] tempp = arr1;
            arr1 = arr2;
            arr2 = tempp;
 
            int temp = m;
            m = n;
            n = temp;
        }
 
        // Now arr1[] is smaller
        // Sort the first array and print
        // its elements (these two steps can
        // be swapped as order in output is
        // not important)
        Array.Sort(arr1);
        for (int i = 0; i < m; i++)
            Console.Write(arr1[i] + " ");
 
        // Search every element of bigger
        // array in smaller array and print
        // the element if not found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
                Console.Write(arr2[i] + " ");
        }
    }
 
    // Prints intersection of arr1[0..m-1]
    // and arr2[0..n-1]
    static void printIntersection(int[] arr1, int[] arr2,
                                  int m, int n)
    {
        // Before finding intersection,
        // make sure arr1[0..m-1] is smaller
        if (m > n) {
            int[] tempp = arr1;
            arr1 = arr2;
            arr2 = tempp;
 
            int temp = m;
            m = n;
            n = temp;
        }
 
        // Now arr1[] is smaller
        // Sort smaller array arr1[0..m-1]
        Array.Sort(arr1);
 
        // Search every element of bigger array in
        // smaller array and print the element if found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
                Console.Write(arr2[i] + " ");
        }
    }
 
    // A recursive binary search function.
    // It returns location of x in given
    // array arr[l..r] is present, otherwise -1
    static int binarySearch(int[] arr, int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;
 
            // If the element is present at
            // the middle itself
            if (arr[mid] == x)
                return mid;
 
            // If element is smaller than mid, then it
            // can only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
 
            // Else the element can only be
            // present in right subarray
            return binarySearch(arr, mid + 1, r, x);
        }
 
        // We reach here when element is
        // not present in array
        return -1;
    }
 
    // Driver Code
    static public void Main()
    {
        int[] arr1 = { 7, 1, 5, 2, 3, 6 };
        int[] arr2 = { 3, 8, 6, 20, 7 };
        int m = arr1.Length;
        int n = arr2.Length;
       
        // Function call
        Console.WriteLine("Union of two arrays is ");
        printUnion(arr1, arr2, m, n);
        Console.WriteLine("");
        Console.WriteLine("Intersection of two arrays is ");
        printIntersection(arr1, arr2, m, n);
    }
}
 
// This code is contributed
// by Sach_Code


PHP
 $n)
    {
        $tempp = $arr1;
        $arr1 = $arr2;
        $arr2 = $tempp;
 
        $temp = $m;
        $m = $n;
        $n = $temp;
    }
 
    // Now arr1[] is smaller
 
    // Sort the first array and print its elements (these two
    // steps can be swapped as order in output is not important)
    sort($arr1);
    for ($i = 0; $i < $m; $i++)
        echo $arr1[$i]." ";
 
    // Search every element of bigger array in smaller array
    // and print the element if not found
    for ($i = 0; $i < $n; $i++)
        if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) == -1)
            echo $arr2[$i]." ";
}
 
// Prints intersection of arr1[0..m-1] and arr2[0..n-1]
function printIntersection($arr1, $arr2, $m, $n)
{
    // Before finding intersection, make sure arr1[0..m-1]
    // is smaller
    if ($m > $n)
    {
        $tempp = $arr1;
        $arr1 = $arr2;
        $arr2 = $tempp;
 
        $temp = $m;
        $m = $n;
        $n = $temp;
    }
 
    // Now arr1[] is smaller
 
    // Sort smaller array arr1[0..m-1]
    sort($arr1);
 
    // Search every element of bigger array in smaller
    // array and print the element if found
    for ($i = 0; $i < $n; $i++)
        if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) != -1)
            echo $arr2[$i]." ";
}
 
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
function binarySearch($arr, $l, $r,$x)
{
    if ($r >= $l)
    {
        $mid = (int)($l + ($r - $l)/2);
 
        // If the element is present at the middle itself
        if ($arr[$mid] == $x) return $mid;
 
        // If element is smaller than mid, then it can only
        // be presen in left subarray
        if ($arr[$mid] > $x)
        return binarySearch($arr, $l, $mid - 1, $x);
 
        // Else the element can only be present in right subarray
        return binarySearch($arr, $mid + 1, $r, $x);
    }
 
    // We reach here when element is not present in array
    return -1;
}
 
/* Driver program to test above function */
    $arr1 = array(7, 1, 5, 2, 3, 6);
    $arr2 = array(3, 8, 6, 20, 7);
    $m = count($arr1);
    $n = count($arr2);
    echo "Union of two arrays is \n";
    printUnion($arr1, $arr2, $m, $n);
    echo "\nIntersection of two arrays is \n";
    printIntersection($arr1, $arr2, $m, $n);
 
// This code is contributed by mits
?>


C++
// C++ code to find intersection when
// elements may not be distinct
#include 
 
using namespace std;
 
// Function to find intersection
void intersection(int a[], int b[], int n, int m)
{
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (a[i] > b[j]) {
            j++;
        }
        else if (b[j] > a[i]) {
            i++;
        }
        else {
             
            // when both are equal
            cout << a[i] << " ";
            i++;
            j++;
        }
    }
}
 
// Driver Code
int main()
{
    int a[] = { 1, 3, 2, 3, 3, 4, 5, 5, 6 };
    int b[] = { 3, 3, 5 };
 
    int n = sizeof(a) / sizeof(a[0]);
    int m = sizeof(b) / sizeof(b[0]);
   
    // sort
    sort(a, a + n);
    sort(b, b + m);
   
    // Function call
    intersection(a, b, n, m);
}


Java
// Java code to find intersection when
// elements may not be distinct
 
import java.io.*;
import java.util.Arrays;
 
class GFG {
 
    // Function to find intersection
    static void intersection(int a[], int b[], int n, int m)
    {
        int i = 0, j = 0;
 
        while (i < n && j < m) {
 
            if (a[i] > b[j]) {
                j++;
            }
 
            else if (b[j] > a[i]) {
                i++;
            }
            else {
                // when both are equal
                System.out.print(a[i] + " ");
                i++;
                j++;
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int a[] = { 1, 3, 2, 3, 4, 5, 5, 6 };
        int b[] = { 3, 3, 5 };
 
        int n = a.length;
        int m = b.length;
       
        // sort
        Arrays.sort(a);
        Arrays.sort(b);
       
        // Function call
        intersection(a, b, n, m);
    }
}


Python3
# Python 3 code to find intersection
# when elements may not be distinct
 
# Function to find intersection
 
 
def intersection(a, b, n, m):
 
    i = 0
    j = 0
 
    while (i < n and j < m):
 
        if (a[i] > b[j]):
            j += 1
 
        else:
            if (b[j] > a[i]):
                i += 1
 
            else:
                # when both are equal
                print(a[i], end=" ")
                i += 1
                j += 1
 
 
# Driver Code
if __name__ == "__main__":
 
    a = [1, 3, 2, 3, 4, 5, 5, 6]
    b = [3, 3, 5]
 
    n = len(a)
    m = len(b)
     
    # sort
    a.sort()
    b.sort()
     
    # function call
    intersection(a, b, n, m)
 
# This code is contributed by Ita_c


C#
// C# code to find intersection when
// elements may not be distinct
 
using System;
 
class GFG {
 
    // Function to find intersection
    static void intersection(int[] a, int[] b, int n, int m)
    {
        int i = 0, j = 0;
 
        while (i < n && j < m) {
 
            if (a[i] > b[j]) {
                j++;
            }
 
            else if (b[j] > a[i]) {
                i++;
            }
            else {
                // when both are equal
                Console.Write(a[i] + " ");
                i++;
                j++;
            }
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int[] a = { 1, 3, 2, 3, 4, 5, 5, 6 };
        int[] b = { 3, 3, 5 };
 
        int n = a.Length;
        int m = b.Length;
       
        // sort
        Array.Sort(a);
        Array.Sort(b);
       
        // Function call
        intersection(a, b, n, m);
    }
}
// this code is contributed by mukul singh


PHP
 $b[$j])
        {
            $j++;
        }
                 
        else
        if ($b[$j] > $a[$i])
        {
            $i++;
        }
        else
        {
            // when both are equal
            echo($a[$i] . " ");
            $i++;
            $j++;
        }
    }
}
 
// Driver Code
$a = array(1, 3, 2, 3, 4, 5, 5, 6);
$b = array(3, 3, 5);
 
$n = sizeof($a);
$m = sizeof($b);
 
// sort
sort($a);
sort($b);
 
// Function call
intersection($a, $b, $n, $m);
 
// This code is contributed
// by Mukul Singh
?>


Javascript


C++
// CPP program to find union and intersection
// using sets
#include 
using namespace std;
 
// Prints union of arr1[0..n1-1] and arr2[0..n2-1]
void printUnion(int arr1[], int arr2[], int n1, int n2)
{
    set hs;
 
    // Inhsert the elements of arr1[] to set hs
    for (int i = 0; i < n1; i++)
        hs.insert(arr1[i]);
 
    // Insert the elements of arr2[] to set hs
    for (int i = 0; i < n2; i++)
        hs.insert(arr2[i]);
 
    // Print the content of set hs
    for (auto it = hs.begin(); it != hs.end(); it++)
        cout << *it << " ";
    cout << endl;
}
 
// Prints intersection of arr1[0..n1-1] and
// arr2[0..n2-1]
void printIntersection(int arr1[], int arr2[], int n1,
                       int n2)
{
    set hs;
 
    // Insert the elements of arr1[] to set S
    for (int i = 0; i < n1; i++)
        hs.insert(arr1[i]);
 
    for (int i = 0; i < n2; i++)
 
        // If element is present in set then
        // push it to vector V
        if (hs.find(arr2[i]) != hs.end())
            cout << arr2[i] << " ";
}
 
// Driver Program
int main()
{
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function call
    printUnion(arr1, arr2, n1, n2);
    printIntersection(arr1, arr2, n1, n2);
 
    return 0;
}


Java
// Java program to find union and intersection
// using Hashing
import java.util.HashSet;
 
class Test {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int arr1[], int arr2[])
    {
        HashSet hs = new HashSet<>();
 
        for (int i = 0; i < arr1.length; i++)
            hs.add(arr1[i]);
        for (int i = 0; i < arr2.length; i++)
            hs.add(arr2[i]);
        System.out.println(hs);
    }
 
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    static void printIntersection(int arr1[], int arr2[])
    {
        HashSet hs = new HashSet<>();
        HashSet hs1 = new HashSet<>();
 
        for (int i = 0; i < arr1.length; i++)
            hs.add(arr1[i]);
 
        for (int i = 0; i < arr2.length; i++)
            if (hs.contains(arr2[i]))
                System.out.print(arr2[i] + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr1[] = { 7, 1, 5, 2, 3, 6 };
        int arr2[] = { 3, 8, 6, 20, 7 };
 
        // Function call
        System.out.println("Union of two arrays is : ");
        printUnion(arr1, arr2);
 
        System.out.println(
            "Intersection of two arrays is : ");
        printIntersection(arr1, arr2);
    }
}


Python
# Python program to find union and intersection
# using sets
 
 
def printUnion(arr1, arr2, n1, n2):
    hs = set()
 
    # Inhsert the elements of arr1[] to set hs
    for i in range(0, n1):
        hs.add(arr1[i])
 
    # Inhsert the elements of arr1[] to set hs
    for i in range(0, n2):
        hs.add(arr2[i])
    print("Union:")
    for i in hs:
        print(i, end=" ")
    print("\n")
 
    # Prints intersection of arr1[0..n1-1] and
    # arr2[0..n2-1]
 
 
def printIntersection(arr1, arr2, n1, n2):
    hs = set()
 
    # Insert the elements of arr1[] to set S
    for i in range(0, n1):
        hs.add(arr1[i])
    print("Intersection:")
    for i in range(0, n2):
 
        # If element is present in set then
        # push it to vector V
        if arr2[i] in hs:
            print(arr2[i], end=" ")
 
 
# Driver Program
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
n1 = len(arr1)
n2 = len(arr2)
 
# Function call
printUnion(arr1, arr2, n1, n2)
printIntersection(arr1, arr2, n1, n2)
 
# This artice is contributed by Kumar Suman .


C#
// C# program to find union and intersection
// using Hashing
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG
{
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int []arr1, int []arr2)
    {
        HashSet hs = new HashSet();
         
        for (int i = 0; i < arr1.Length; i++)
            hs.Add(arr1[i]);    
        for (int i = 0; i < arr2.Length; i++)
            hs.Add(arr2[i]);
     
            Console.WriteLine(string.Join(", ", hs));    
    }
     
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    static void printIntersection(int []arr1, int []arr2)
    {
        HashSet hs = new HashSet();
         
        for (int i = 0; i < arr1.Length; i++)
            hs.Add(arr1[i]);
         
        for (int i = 0; i < arr2.Length; i++)
            if (hs.Contains(arr2[i]))
            Console.Write(arr2[i] + " ");
    }
     
    // Driver Code
    static void Main()
    {
        int []arr1 = {7, 1, 5, 2, 3, 6};
        int []arr2 = {3, 8, 6, 20, 7};
 
        Console.WriteLine("Union of two arrays is : ");
        printUnion(arr1, arr2);
     
        Console.WriteLine("\nIntersection of two arrays is : ");
        printIntersection(arr1, arr2);
    }
}
 
// This code is contributed by mits


Java
// Java program to find union and intersection
// using similar Hashing Technique
// without using any predefined Java Collections
// Time Complexity best case & avg case = O(m+n)
// Worst case = O(nlogn)
 
// package com.arrays.math;
 
public class UnsortedIntersectionUnion {
 
    // Prints intersection of arr1[0..n1-1] and
    // arr2[0..n2-1]
    public void findPosition(int a[], int b[])
    {
        int v = (a.length + b.length);
        int ans[] = new int[v];
 
        int zero1 = 0;
        int zero2 = 0;
 
        System.out.print("Intersection : ");
        // Iterate first array
        for (int i = 0; i < a.length; i++)
            zero1 = iterateArray(a, v, ans, i);
 
        // Iterate second array
        for (int j = 0; j < b.length; j++)
            zero2 = iterateArray(b, v, ans, j);
 
        int zero = zero1 + zero2;
        placeZeros(v, ans, zero);
        printUnion(v, ans, zero);
    }
 
    // Prints union of arr1[0..n1-1] and arr2[0..n2-1]
    private void printUnion(int v, int[] ans, int zero)
    {
        int zero1 = 0;
        System.out.print("\nUnion : ");
        for (int i = 0; i < v; i++) {
            if ((zero == 0 && ans[i] == 0)
                || (ans[i] == 0 && zero1 > 0))
                continue;
            if (ans[i] == 0)
                zero1++;
            System.out.print(ans[i] + ",");
        }
    }
 
    private void placeZeros(int v, int[] ans, int zero)
    {
        if (zero == 2) {
            System.out.println("0");
            int d[] = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
        if (zero == 1) {
            int d[] = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
    }
 
    // Function to itreate array
    private int iterateArray(int[] a, int v, int[] ans,
                             int i)
    {
        if (a[i] != 0) {
            int p = a[i] % v;
            placeValue(a, ans, i, p, v);
        }
        else
            return 1;
        return 0;
    }
 
    private void placeValue(int[] a, int[] ans, int i,
                            int p, int v)
    {
        p = p % v;
        if (ans[p] == 0)
            ans[p] = a[i];
        else {
            if (ans[p] == a[i])
                System.out.print(a[i] + ",");
            else {
 
                // Hashing collision happened increment
                // position and do recursive call
                p = p + 1;
                placeValue(a, ans, i, p, v);
            }
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int a[] = { 7, 1, 5, 2, 3, 6 };
        int b[] = { 3, 8, 6, 20, 7 };
 
        // Function call
        UnsortedIntersectionUnion uiu
            = new UnsortedIntersectionUnion();
        uiu.findPosition(a, b);
    }
}
// This code is contributed by Mohanakrishnan S.


Python3
# Python3 program to find union and intersection
# using similar Hashing Technique
# without using any predefined Java Collections
# Time Complexity best case & avg case = O(m+n)
# Worst case = O(nlogn)
 
 
# Prints intersection of arr1[0..n1-1] and
# arr2[0..n2-1]
def findPosition(a, b):
    v = len(a) + len(b);
    ans = [0]*v;
    zero1 = zero2 = 0;
    print("Intersection :",end=" ");
     
    # Iterate first array
    for i in range(len(a)):
        zero1 = iterateArray(a, v, ans, i);
     
    # Iterate second array
    for j in range(len(b)):
        zero2 = iterateArray(b, v, ans, j);
     
    zero = zero1 + zero2;
    placeZeros(v, ans, zero);
    printUnion(v, ans, zero);
     
# Prints union of arr1[0..n1-1] and arr2[0..n2-1]
def printUnion(v, ans,zero):
    zero1 = 0;
    print("\nUnion :",end=" ");
    for i in range(v):
        if ((zero == 0 and ans[i] == 0) or
            (ans[i] == 0 and zero1 > 0)):
            continue;
        if (ans[i] == 0):
            zero1+=1;
        print(ans[i],end=",");
 
def placeZeros(v, ans, zero):
    if (zero == 2):
        print("0");
        d = [0];
        placeValue(d, ans, 0, 0, v);
    if (zero == 1):
        d=[0];
        placeValue(d, ans, 0, 0, v);
 
# Function to itreate array
def iterateArray(a,v,ans,i):
    if (a[i] != 0):
        p = a[i] % v;
        placeValue(a, ans, i, p, v);
    else:
        return 1;
     
    return 0;
 
def placeValue(a,ans,i,p,v):
    p = p % v;
    if (ans[p] == 0):
        ans[p] = a[i];
    else:
        if (ans[p] == a[i]):
            print(a[i],end=",");
        else:
            # Hashing collision happened increment
            # position and do recursive call
            p = p + 1;
            placeValue(a, ans, i, p, v);
 
# Driver code
a = [ 7, 1, 5, 2, 3, 6 ];
b = [ 3, 8, 6, 20, 7 ];
findPosition(a, b);
 
# This code is contributed by mits


C#
// C# program to find union and intersection
// using similar Hashing Technique
// without using any predefined Java Collections
// Time Complexity best case & avg case = O(m+n)
// Worst case = O(nlogn)
 
//package com.arrays.math;
using System;
class UnsortedIntersectionUnion
{
 
        // Prints intersection of arr1[0..n1-1] and
        // arr2[0..n2-1]
    public void findPosition(int []a, int []b)
    {
        int v = (a.Length + b.Length);
        int []ans = new int[v];
 
        int zero1 = 0;
        int zero2 = 0;
 
        Console.Write("Intersection : ");
         
        // Iterate first array
        for (int i = 0; i < a.Length; i++)
            zero1 = iterateArray(a, v, ans, i);
 
        // Iterate second array
        for (int j = 0; j < b.Length; j++)
            zero2 = iterateArray(b, v, ans, j);
 
        int zero = zero1 + zero2;
        placeZeros(v, ans, zero);
        printUnion(v, ans, zero);
 
    }
     
    // Prints union of arr1[0..n1-1]
    // and arr2[0..n2-1]
    private void printUnion(int v, int[] ans, int zero)
    {
        int zero1 = 0;
        Console.Write("\nUnion : ");
        for (int i = 0; i < v; i++)
        {
            if ((zero == 0 && ans[i] == 0) ||
                    (ans[i] == 0 && zero1 > 0))
                continue;
            if (ans[i] == 0)
                zero1++;
            Console.Write(ans[i] + ",");
        }
    }
 
    private void placeZeros(int v, int[] ans, int zero)
    {
        if (zero == 2)
        {
            Console.WriteLine("0");
            int []d = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
        if (zero == 1)
        {
            int []d = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
    }
 
    // Function to itreate array
    private int iterateArray(int[] a, int v,
                            int[] ans, int i)
    {
        if (a[i] != 0)
        {
            int p = a[i] % v;
            placeValue(a, ans, i, p, v);
        } else
            return 1;
        return 0;
    }
 
    private void placeValue(int[] a, int[] ans,
                                int i, int p, int v)
    {
        p = p % v;
        if (ans[p] == 0)
            ans[p] = a[i];
        else {
            if (ans[p] == a[i])
                Console.Write(a[i] + ",");
            else
            {
                 
                //Hashing collision happened increment
                // position and do recursive call
                p = p + 1;
                placeValue(a, ans, i, p, v);
            }
        }
    }
 
    // Driver code
    public static void Main()
    {
        int []a = { 7, 1, 5, 2, 3, 6 };
        int []b = { 3, 8, 6, 20, 7 };
 
        UnsortedIntersectionUnion uiu = new UnsortedIntersectionUnion();
        uiu.findPosition(a, b);
    }
}
 
// This code is contributed by PrinciRaj1992


Python3
#  Python program to find union and intersection
#  using sets
 
 
def printUnion(arr1, arr2, n1, n2):
    hs = set()
    #  Inhsert the elements of arr1[] to set hs
    for i in range(0, n1):
        hs.add(arr1[i])
    #  Inhsert the elements of arr1[] to set hs
    for i in range(0, n2):
        hs.add(arr2[i])
    print("Union:")
    for i in hs:
        print(i, end=" ")
    print("\n")
    #  Prints intersection of arr1[0..n1-1] and
    #  arr2[0..n2-1]
 
 
def printIntersection(arr1, arr2, n1, n2):
    hs = set()
    #  Insert the elements of arr1[] to set S
    for i in range(0, n1):
        hs.add(arr1[i])
    print("Intersection:")
    for i in range(0, n2):
        #  If element is present in set then
        #  push it to vector V
        if arr2[i] in hs:
            print(arr2[i], end=" ")
 
 
#  Driver Program
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
n1 = len(arr1)
n2 = len(arr2)
 
# Function call
printUnion(arr1, arr2, n1, n2)
printIntersection(arr1, arr2, n1, n2)
 
# This artice is contributed by Kumar Suman .


输出

The union set of both arrays is :
1 2 3 4 5 6 8 9

上述方法具有时间复杂度O(m + n)。

*此方法由Vinay Verma建议

方法2(天真)
联盟:  

  1. 将联合U初始化为空。
  2. 将第一个数组的所有元素复制到U。
  3. 对第二个数组的每个元素x执行以下操作:
    1. 如果第一个数组中不存在x,则将x复制到U。
  4. 返回U。

路口:

  1. 将交集I初始化为空。
  2. 对第一个数组的每个元素x执行以下操作
    1. 如果第二个数组中存在x,则将x复制到I。
  3. 还给我

对于两种操作,此方法的时间复杂度均为O(mn)。其中,m和n分别是arr1 []和arr2 []中的元素数。

方法3(使用排序)

  1. 排序arr1 []和arr2 []。此步骤需要O(mLogm + nLogn)时间。
  2. 使用O(m + n)算法查找两个排序数组的并集和交集。

此方法的总时间复杂度为O(mLogm + nLogn)。

方法4(使用排序和搜索)
联盟:

  1. 将联合U初始化为空。
  2. 查找较小的m和n并对较小的数组进行排序。
  3. 将较小的数组复制到U。
  4. 对于较大数组的每个元素x,请执行以下操作
    1. 二进制搜索x较小的数组。如果x不存在,则将其复制到U。
  5. 返回U。

路口:

  1. 将交集I初始化为空。
  2. 查找较小的m和n并对较小的数组进行排序。
  3. 对于较大数组的每个元素x,请执行以下操作
    1. 二进制搜索x较小的数组。如果存在x,则将其复制到I。
  4. 还给我

该方法的时间复杂度是min(mLogm + nLogm,mLogn + nLogn),也可以写成O((m + n)Logm,(m + n)Logn)。当两个阵列的大小之间的差异很大时,此方法比以前的方法要好得多。
感谢use_the_force在此处的注释中建议此方法。

下面是此方法的实现。

C++

// A C++ program to print union and intersection
/// of two unsorted arrays
#include 
#include 
using namespace std;
 
int binarySearch(int arr[], int l, int r, int x);
 
// Prints union of arr1[0..m-1] and arr2[0..n-1]
void printUnion(int arr1[], int arr2[], int m, int n)
{
    // Before finding union, make sure arr1[0..m-1]
    // is smaller
    if (m > n) {
        int* tempp = arr1;
        arr1 = arr2;
        arr2 = tempp;
 
        int temp = m;
        m = n;
        n = temp;
    }
 
    // Now arr1[] is smaller
 
    // Sort the first array and print its elements (these
    // two steps can be swapped as order in output is not
    // important)
    sort(arr1, arr1 + m);
    for (int i = 0; i < m; i++)
        cout << arr1[i] << " ";
 
    // Search every element of bigger array in smaller array
    // and print the element if not found
    for (int i = 0; i < n; i++)
        if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
            cout << arr2[i] << " ";
}
 
// Prints intersection of arr1[0..m-1] and arr2[0..n-1]
void printIntersection(int arr1[], int arr2[], int m, int n)
{
    // Before finding intersection, make sure arr1[0..m-1]
    // is smaller
    if (m > n) {
        int* tempp = arr1;
        arr1 = arr2;
        arr2 = tempp;
 
        int temp = m;
        m = n;
        n = temp;
    }
 
    // Now arr1[] is smaller
 
    // Sort smaller array arr1[0..m-1]
    sort(arr1, arr1 + m);
 
    // Search every element of bigger array in smaller
    // array and print the element if found
    for (int i = 0; i < n; i++)
        if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
            cout << arr2[i] << " ";
}
 
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
    if (r >= l) {
        int mid = l + (r - l) / 2;
 
        // If the element is present at the middle itself
        if (arr[mid] == x)
            return mid;
 
        // If element is smaller than mid, then it can only
        // be presen in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);
 
        // Else the element can only be present in right
        // subarray
        return binarySearch(arr, mid + 1, r, x);
    }
 
    // We reach here when element is not present in array
    return -1;
}
 
/* Driver program to test above function */
int main()
{
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
   
    // Function call
    cout << "Union of two arrays is n";
    printUnion(arr1, arr2, m, n);
    cout << "nIntersection of two arrays is n";
    printIntersection(arr1, arr2, m, n);
    return 0;
}

Java

// A Java program to print union and intersection
/// of two unsorted arrays
import java.util.Arrays;
 
class UnionAndIntersection {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    void printUnion(int arr1[], int arr2[], int m, int n)
    {
        // Before finding union, make sure arr1[0..m-1]
        // is smaller
        if (m > n) {
            int tempp[] = arr1;
            arr1 = arr2;
            arr2 = tempp;
 
            int temp = m;
            m = n;
            n = temp;
        }
 
        // Now arr1[] is smaller
        // Sort the first array and print its elements
        // (these two steps can be swapped as order in
        // output is not important)
        Arrays.sort(arr1);
        for (int i = 0; i < m; i++)
            System.out.print(arr1[i] + " ");
 
        // Search every element of bigger array in smaller
        // array and print the element if not found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
                System.out.print(arr2[i] + " ");
        }
    }
 
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    void printIntersection(int arr1[], int arr2[], int m,
                           int n)
    {
        // Before finding intersection, make sure
        // arr1[0..m-1] is smaller
        if (m > n) {
            int tempp[] = arr1;
            arr1 = arr2;
            arr2 = tempp;
 
            int temp = m;
            m = n;
            n = temp;
        }
 
        // Now arr1[] is smaller
        // Sort smaller array arr1[0..m-1]
        Arrays.sort(arr1);
 
        // Search every element of bigger array in smaller
        // array and print the element if found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
                System.out.print(arr2[i] + " ");
        }
    }
 
    // A recursive binary search function. It returns
    // location of x in given array arr[l..r] is present,
    // otherwise -1
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;
 
            // If the element is present at the middle
            // itself
            if (arr[mid] == x)
                return mid;
 
            // If element is smaller than mid, then it can
            // only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
 
            // Else the element can only be present in right
            // subarray
            return binarySearch(arr, mid + 1, r, x);
        }
 
        // We reach here when element is not present in
        // array
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        UnionAndIntersection u_i
            = new UnionAndIntersection();
        int arr1[] = { 7, 1, 5, 2, 3, 6 };
        int arr2[] = { 3, 8, 6, 20, 7 };
        int m = arr1.length;
        int n = arr2.length;
       
        // Function call
        System.out.println("Union of two arrays is ");
        u_i.printUnion(arr1, arr2, m, n);
        System.out.println("");
        System.out.println(
            "Intersection of two arrays is ");
        u_i.printIntersection(arr1, arr2, m, n);
    }
}

Python3

# A Python3 program to print union and intersection
# of two unsorted arrays
 
# Prints union of arr1[0..m-1] and arr2[0..n-1]
 
 
def printUnion(arr1, arr2, m, n):
 
    # Before finding union, make sure arr1[0..m-1]
    # is smaller
    if (m > n):
        tempp = arr1
        arr1 = arr2
        arr2 = tempp
 
        temp = m
        m = n
        n = temp
 
    # Now arr1[] is smaller
 
    # Sort the first array and print its elements (these two
    # steps can be swapped as order in output is not important)
    arr1.sort()
    for i in range(0, m):
        print(arr1[i], end=" ")
 
    # Search every element of bigger array in smaller array
    # and print the element if not found
    for i in range(0, n):
        if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1):
            print(arr2[i], end=" ")
 
# Prints intersection of arr1[0..m-1] and arr2[0..n-1]
 
 
def printIntersection(arr1, arr2, m, n):
 
    # Before finding intersection, make sure arr1[0..m-1]
    # is smaller
    if (m > n):
        tempp = arr1
        arr1 = arr2
        arr2 = tempp
 
        temp = m
        m = n
        n = temp
 
    # Now arr1[] is smaller
 
    # Sort smaller array arr1[0..m-1]
    arr1.sort()
 
    # Search every element of bigger array in smaller
    # array and print the element if found
    for i in range(0, n):
        if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1):
            print(arr2[i], end=" ")
 
# A recursive binary search function. It returns
# location of x in given array arr[l..r] is present,
# otherwise -1
 
 
def binarySearch(arr, l, r, x):
 
    if (r >= l):
        mid = int(l + (r - l)/2)
 
        # If the element is present at the middle itself
        if (arr[mid] == x):
            return mid
 
        # If element is smaller than mid, then it can only
        # be presen in left subarray
        if (arr[mid] > x):
            return binarySearch(arr, l, mid - 1, x)
 
        # Else the element can only be present in right subarray
        return binarySearch(arr, mid + 1, r, x)
 
    # We reach here when element is not present in array
    return -1
 
 
# Driver code
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
m = len(arr1)
n = len(arr2)
 
# Function call
print("Union of two arrays is ")
printUnion(arr1, arr2, m, n)
print("\nIntersection of two arrays is ")
printIntersection(arr1, arr2, m, n)
 
# This code is contributed by mits

C#

// A C# program to print union and
// intersection of two unsorted arrays
using System;
 
class GFG {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int[] arr1, int[] arr2, int m,
                           int n)
    {
        // Before finding union, make
        // sure arr1[0..m-1] is smaller
        if (m > n) {
            int[] tempp = arr1;
            arr1 = arr2;
            arr2 = tempp;
 
            int temp = m;
            m = n;
            n = temp;
        }
 
        // Now arr1[] is smaller
        // Sort the first array and print
        // its elements (these two steps can
        // be swapped as order in output is
        // not important)
        Array.Sort(arr1);
        for (int i = 0; i < m; i++)
            Console.Write(arr1[i] + " ");
 
        // Search every element of bigger
        // array in smaller array and print
        // the element if not found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1)
                Console.Write(arr2[i] + " ");
        }
    }
 
    // Prints intersection of arr1[0..m-1]
    // and arr2[0..n-1]
    static void printIntersection(int[] arr1, int[] arr2,
                                  int m, int n)
    {
        // Before finding intersection,
        // make sure arr1[0..m-1] is smaller
        if (m > n) {
            int[] tempp = arr1;
            arr1 = arr2;
            arr2 = tempp;
 
            int temp = m;
            m = n;
            n = temp;
        }
 
        // Now arr1[] is smaller
        // Sort smaller array arr1[0..m-1]
        Array.Sort(arr1);
 
        // Search every element of bigger array in
        // smaller array and print the element if found
        for (int i = 0; i < n; i++) {
            if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1)
                Console.Write(arr2[i] + " ");
        }
    }
 
    // A recursive binary search function.
    // It returns location of x in given
    // array arr[l..r] is present, otherwise -1
    static int binarySearch(int[] arr, int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;
 
            // If the element is present at
            // the middle itself
            if (arr[mid] == x)
                return mid;
 
            // If element is smaller than mid, then it
            // can only be present in left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
 
            // Else the element can only be
            // present in right subarray
            return binarySearch(arr, mid + 1, r, x);
        }
 
        // We reach here when element is
        // not present in array
        return -1;
    }
 
    // Driver Code
    static public void Main()
    {
        int[] arr1 = { 7, 1, 5, 2, 3, 6 };
        int[] arr2 = { 3, 8, 6, 20, 7 };
        int m = arr1.Length;
        int n = arr2.Length;
       
        // Function call
        Console.WriteLine("Union of two arrays is ");
        printUnion(arr1, arr2, m, n);
        Console.WriteLine("");
        Console.WriteLine("Intersection of two arrays is ");
        printIntersection(arr1, arr2, m, n);
    }
}
 
// This code is contributed
// by Sach_Code

的PHP

 $n)
    {
        $tempp = $arr1;
        $arr1 = $arr2;
        $arr2 = $tempp;
 
        $temp = $m;
        $m = $n;
        $n = $temp;
    }
 
    // Now arr1[] is smaller
 
    // Sort the first array and print its elements (these two
    // steps can be swapped as order in output is not important)
    sort($arr1);
    for ($i = 0; $i < $m; $i++)
        echo $arr1[$i]." ";
 
    // Search every element of bigger array in smaller array
    // and print the element if not found
    for ($i = 0; $i < $n; $i++)
        if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) == -1)
            echo $arr2[$i]." ";
}
 
// Prints intersection of arr1[0..m-1] and arr2[0..n-1]
function printIntersection($arr1, $arr2, $m, $n)
{
    // Before finding intersection, make sure arr1[0..m-1]
    // is smaller
    if ($m > $n)
    {
        $tempp = $arr1;
        $arr1 = $arr2;
        $arr2 = $tempp;
 
        $temp = $m;
        $m = $n;
        $n = $temp;
    }
 
    // Now arr1[] is smaller
 
    // Sort smaller array arr1[0..m-1]
    sort($arr1);
 
    // Search every element of bigger array in smaller
    // array and print the element if found
    for ($i = 0; $i < $n; $i++)
        if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) != -1)
            echo $arr2[$i]." ";
}
 
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
function binarySearch($arr, $l, $r,$x)
{
    if ($r >= $l)
    {
        $mid = (int)($l + ($r - $l)/2);
 
        // If the element is present at the middle itself
        if ($arr[$mid] == $x) return $mid;
 
        // If element is smaller than mid, then it can only
        // be presen in left subarray
        if ($arr[$mid] > $x)
        return binarySearch($arr, $l, $mid - 1, $x);
 
        // Else the element can only be present in right subarray
        return binarySearch($arr, $mid + 1, $r, $x);
    }
 
    // We reach here when element is not present in array
    return -1;
}
 
/* Driver program to test above function */
    $arr1 = array(7, 1, 5, 2, 3, 6);
    $arr2 = array(3, 8, 6, 20, 7);
    $m = count($arr1);
    $n = count($arr2);
    echo "Union of two arrays is \n";
    printUnion($arr1, $arr2, $m, $n);
    echo "\nIntersection of two arrays is \n";
    printIntersection($arr1, $arr2, $m, $n);
 
// This code is contributed by mits
?>
输出
Union of two arrays is n3 6 7 8 20 1 5 2 nIntersection of two arrays is n7 3 6

另一种方法(当数组中的元素可能不同时):

C++

// C++ code to find intersection when
// elements may not be distinct
#include 
 
using namespace std;
 
// Function to find intersection
void intersection(int a[], int b[], int n, int m)
{
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (a[i] > b[j]) {
            j++;
        }
        else if (b[j] > a[i]) {
            i++;
        }
        else {
             
            // when both are equal
            cout << a[i] << " ";
            i++;
            j++;
        }
    }
}
 
// Driver Code
int main()
{
    int a[] = { 1, 3, 2, 3, 3, 4, 5, 5, 6 };
    int b[] = { 3, 3, 5 };
 
    int n = sizeof(a) / sizeof(a[0]);
    int m = sizeof(b) / sizeof(b[0]);
   
    // sort
    sort(a, a + n);
    sort(b, b + m);
   
    // Function call
    intersection(a, b, n, m);
}

Java

// Java code to find intersection when
// elements may not be distinct
 
import java.io.*;
import java.util.Arrays;
 
class GFG {
 
    // Function to find intersection
    static void intersection(int a[], int b[], int n, int m)
    {
        int i = 0, j = 0;
 
        while (i < n && j < m) {
 
            if (a[i] > b[j]) {
                j++;
            }
 
            else if (b[j] > a[i]) {
                i++;
            }
            else {
                // when both are equal
                System.out.print(a[i] + " ");
                i++;
                j++;
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int a[] = { 1, 3, 2, 3, 4, 5, 5, 6 };
        int b[] = { 3, 3, 5 };
 
        int n = a.length;
        int m = b.length;
       
        // sort
        Arrays.sort(a);
        Arrays.sort(b);
       
        // Function call
        intersection(a, b, n, m);
    }
}

Python3

# Python 3 code to find intersection
# when elements may not be distinct
 
# Function to find intersection
 
 
def intersection(a, b, n, m):
 
    i = 0
    j = 0
 
    while (i < n and j < m):
 
        if (a[i] > b[j]):
            j += 1
 
        else:
            if (b[j] > a[i]):
                i += 1
 
            else:
                # when both are equal
                print(a[i], end=" ")
                i += 1
                j += 1
 
 
# Driver Code
if __name__ == "__main__":
 
    a = [1, 3, 2, 3, 4, 5, 5, 6]
    b = [3, 3, 5]
 
    n = len(a)
    m = len(b)
     
    # sort
    a.sort()
    b.sort()
     
    # function call
    intersection(a, b, n, m)
 
# This code is contributed by Ita_c

C#

// C# code to find intersection when
// elements may not be distinct
 
using System;
 
class GFG {
 
    // Function to find intersection
    static void intersection(int[] a, int[] b, int n, int m)
    {
        int i = 0, j = 0;
 
        while (i < n && j < m) {
 
            if (a[i] > b[j]) {
                j++;
            }
 
            else if (b[j] > a[i]) {
                i++;
            }
            else {
                // when both are equal
                Console.Write(a[i] + " ");
                i++;
                j++;
            }
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int[] a = { 1, 3, 2, 3, 4, 5, 5, 6 };
        int[] b = { 3, 3, 5 };
 
        int n = a.Length;
        int m = b.Length;
       
        // sort
        Array.Sort(a);
        Array.Sort(b);
       
        // Function call
        intersection(a, b, n, m);
    }
}
// this code is contributed by mukul singh

的PHP

 $b[$j])
        {
            $j++;
        }
                 
        else
        if ($b[$j] > $a[$i])
        {
            $i++;
        }
        else
        {
            // when both are equal
            echo($a[$i] . " ");
            $i++;
            $j++;
        }
    }
}
 
// Driver Code
$a = array(1, 3, 2, 3, 4, 5, 5, 6);
$b = array(3, 3, 5);
 
$n = sizeof($a);
$m = sizeof($b);
 
// sort
sort($a);
sort($b);
 
// Function call
intersection($a, $b, $n, $m);
 
// This code is contributed
// by Mukul Singh
?>

Java脚本


输出
3 3 5

感谢Sanny Kumar建议使用上述方法。

方法5(使用散列)
联盟

  1. 初始化一个空的哈希集hs
  2. 遍历第一个数组并将第一个数组的每个元素放入集合S中。
  3. 对第二个数组重复该过程。
  4. 打印设置hs

路口

  1. 初始化一个空集hs。
  2. 遍历第一个数组并将第一个数组的每个元素放入集合S中。
  3. 对于第二个数组的每个元素x,请执行以下操作:

在集合hs中搜索x。如果存在x,则打印它。在哈希表搜索和插入操作花费λ(1)时间的假设下,此方法的时间复杂度为λ(m + n)。
下面是上述想法的实现:

C++

// CPP program to find union and intersection
// using sets
#include 
using namespace std;
 
// Prints union of arr1[0..n1-1] and arr2[0..n2-1]
void printUnion(int arr1[], int arr2[], int n1, int n2)
{
    set hs;
 
    // Inhsert the elements of arr1[] to set hs
    for (int i = 0; i < n1; i++)
        hs.insert(arr1[i]);
 
    // Insert the elements of arr2[] to set hs
    for (int i = 0; i < n2; i++)
        hs.insert(arr2[i]);
 
    // Print the content of set hs
    for (auto it = hs.begin(); it != hs.end(); it++)
        cout << *it << " ";
    cout << endl;
}
 
// Prints intersection of arr1[0..n1-1] and
// arr2[0..n2-1]
void printIntersection(int arr1[], int arr2[], int n1,
                       int n2)
{
    set hs;
 
    // Insert the elements of arr1[] to set S
    for (int i = 0; i < n1; i++)
        hs.insert(arr1[i]);
 
    for (int i = 0; i < n2; i++)
 
        // If element is present in set then
        // push it to vector V
        if (hs.find(arr2[i]) != hs.end())
            cout << arr2[i] << " ";
}
 
// Driver Program
int main()
{
    int arr1[] = { 7, 1, 5, 2, 3, 6 };
    int arr2[] = { 3, 8, 6, 20, 7 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function call
    printUnion(arr1, arr2, n1, n2);
    printIntersection(arr1, arr2, n1, n2);
 
    return 0;
}

Java

// Java program to find union and intersection
// using Hashing
import java.util.HashSet;
 
class Test {
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int arr1[], int arr2[])
    {
        HashSet hs = new HashSet<>();
 
        for (int i = 0; i < arr1.length; i++)
            hs.add(arr1[i]);
        for (int i = 0; i < arr2.length; i++)
            hs.add(arr2[i]);
        System.out.println(hs);
    }
 
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    static void printIntersection(int arr1[], int arr2[])
    {
        HashSet hs = new HashSet<>();
        HashSet hs1 = new HashSet<>();
 
        for (int i = 0; i < arr1.length; i++)
            hs.add(arr1[i]);
 
        for (int i = 0; i < arr2.length; i++)
            if (hs.contains(arr2[i]))
                System.out.print(arr2[i] + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr1[] = { 7, 1, 5, 2, 3, 6 };
        int arr2[] = { 3, 8, 6, 20, 7 };
 
        // Function call
        System.out.println("Union of two arrays is : ");
        printUnion(arr1, arr2);
 
        System.out.println(
            "Intersection of two arrays is : ");
        printIntersection(arr1, arr2);
    }
}

Python

# Python program to find union and intersection
# using sets
 
 
def printUnion(arr1, arr2, n1, n2):
    hs = set()
 
    # Inhsert the elements of arr1[] to set hs
    for i in range(0, n1):
        hs.add(arr1[i])
 
    # Inhsert the elements of arr1[] to set hs
    for i in range(0, n2):
        hs.add(arr2[i])
    print("Union:")
    for i in hs:
        print(i, end=" ")
    print("\n")
 
    # Prints intersection of arr1[0..n1-1] and
    # arr2[0..n2-1]
 
 
def printIntersection(arr1, arr2, n1, n2):
    hs = set()
 
    # Insert the elements of arr1[] to set S
    for i in range(0, n1):
        hs.add(arr1[i])
    print("Intersection:")
    for i in range(0, n2):
 
        # If element is present in set then
        # push it to vector V
        if arr2[i] in hs:
            print(arr2[i], end=" ")
 
 
# Driver Program
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
n1 = len(arr1)
n2 = len(arr2)
 
# Function call
printUnion(arr1, arr2, n1, n2)
printIntersection(arr1, arr2, n1, n2)
 
# This artice is contributed by Kumar Suman .

C#

// C# program to find union and intersection
// using Hashing
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG
{
    // Prints union of arr1[0..m-1] and arr2[0..n-1]
    static void printUnion(int []arr1, int []arr2)
    {
        HashSet hs = new HashSet();
         
        for (int i = 0; i < arr1.Length; i++)
            hs.Add(arr1[i]);    
        for (int i = 0; i < arr2.Length; i++)
            hs.Add(arr2[i]);
     
            Console.WriteLine(string.Join(", ", hs));    
    }
     
    // Prints intersection of arr1[0..m-1] and arr2[0..n-1]
    static void printIntersection(int []arr1, int []arr2)
    {
        HashSet hs = new HashSet();
         
        for (int i = 0; i < arr1.Length; i++)
            hs.Add(arr1[i]);
         
        for (int i = 0; i < arr2.Length; i++)
            if (hs.Contains(arr2[i]))
            Console.Write(arr2[i] + " ");
    }
     
    // Driver Code
    static void Main()
    {
        int []arr1 = {7, 1, 5, 2, 3, 6};
        int []arr2 = {3, 8, 6, 20, 7};
 
        Console.WriteLine("Union of two arrays is : ");
        printUnion(arr1, arr2);
     
        Console.WriteLine("\nIntersection of two arrays is : ");
        printIntersection(arr1, arr2);
    }
}
 
// This code is contributed by mits
输出
1 2 3 5 6 7 8 20 
3 6 7

该方法由Ankur Singh贡献。

方法6(不使用任何预定义的Java集合的哈希技术的种类)

  1. 初始化大小为m + n的数组
  2. 通过进行哈希处理(找到合适的位置),将第一个数组值填充到结果数组中
  3. 重复第二个数组
  4. 在进行散列时,如果发生冲突,则以递归的方式增加位置

下面是上述代码的实现:

Java

// Java program to find union and intersection
// using similar Hashing Technique
// without using any predefined Java Collections
// Time Complexity best case & avg case = O(m+n)
// Worst case = O(nlogn)
 
// package com.arrays.math;
 
public class UnsortedIntersectionUnion {
 
    // Prints intersection of arr1[0..n1-1] and
    // arr2[0..n2-1]
    public void findPosition(int a[], int b[])
    {
        int v = (a.length + b.length);
        int ans[] = new int[v];
 
        int zero1 = 0;
        int zero2 = 0;
 
        System.out.print("Intersection : ");
        // Iterate first array
        for (int i = 0; i < a.length; i++)
            zero1 = iterateArray(a, v, ans, i);
 
        // Iterate second array
        for (int j = 0; j < b.length; j++)
            zero2 = iterateArray(b, v, ans, j);
 
        int zero = zero1 + zero2;
        placeZeros(v, ans, zero);
        printUnion(v, ans, zero);
    }
 
    // Prints union of arr1[0..n1-1] and arr2[0..n2-1]
    private void printUnion(int v, int[] ans, int zero)
    {
        int zero1 = 0;
        System.out.print("\nUnion : ");
        for (int i = 0; i < v; i++) {
            if ((zero == 0 && ans[i] == 0)
                || (ans[i] == 0 && zero1 > 0))
                continue;
            if (ans[i] == 0)
                zero1++;
            System.out.print(ans[i] + ",");
        }
    }
 
    private void placeZeros(int v, int[] ans, int zero)
    {
        if (zero == 2) {
            System.out.println("0");
            int d[] = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
        if (zero == 1) {
            int d[] = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
    }
 
    // Function to itreate array
    private int iterateArray(int[] a, int v, int[] ans,
                             int i)
    {
        if (a[i] != 0) {
            int p = a[i] % v;
            placeValue(a, ans, i, p, v);
        }
        else
            return 1;
        return 0;
    }
 
    private void placeValue(int[] a, int[] ans, int i,
                            int p, int v)
    {
        p = p % v;
        if (ans[p] == 0)
            ans[p] = a[i];
        else {
            if (ans[p] == a[i])
                System.out.print(a[i] + ",");
            else {
 
                // Hashing collision happened increment
                // position and do recursive call
                p = p + 1;
                placeValue(a, ans, i, p, v);
            }
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int a[] = { 7, 1, 5, 2, 3, 6 };
        int b[] = { 3, 8, 6, 20, 7 };
 
        // Function call
        UnsortedIntersectionUnion uiu
            = new UnsortedIntersectionUnion();
        uiu.findPosition(a, b);
    }
}
// This code is contributed by Mohanakrishnan S.

Python3

# Python3 program to find union and intersection
# using similar Hashing Technique
# without using any predefined Java Collections
# Time Complexity best case & avg case = O(m+n)
# Worst case = O(nlogn)
 
 
# Prints intersection of arr1[0..n1-1] and
# arr2[0..n2-1]
def findPosition(a, b):
    v = len(a) + len(b);
    ans = [0]*v;
    zero1 = zero2 = 0;
    print("Intersection :",end=" ");
     
    # Iterate first array
    for i in range(len(a)):
        zero1 = iterateArray(a, v, ans, i);
     
    # Iterate second array
    for j in range(len(b)):
        zero2 = iterateArray(b, v, ans, j);
     
    zero = zero1 + zero2;
    placeZeros(v, ans, zero);
    printUnion(v, ans, zero);
     
# Prints union of arr1[0..n1-1] and arr2[0..n2-1]
def printUnion(v, ans,zero):
    zero1 = 0;
    print("\nUnion :",end=" ");
    for i in range(v):
        if ((zero == 0 and ans[i] == 0) or
            (ans[i] == 0 and zero1 > 0)):
            continue;
        if (ans[i] == 0):
            zero1+=1;
        print(ans[i],end=",");
 
def placeZeros(v, ans, zero):
    if (zero == 2):
        print("0");
        d = [0];
        placeValue(d, ans, 0, 0, v);
    if (zero == 1):
        d=[0];
        placeValue(d, ans, 0, 0, v);
 
# Function to itreate array
def iterateArray(a,v,ans,i):
    if (a[i] != 0):
        p = a[i] % v;
        placeValue(a, ans, i, p, v);
    else:
        return 1;
     
    return 0;
 
def placeValue(a,ans,i,p,v):
    p = p % v;
    if (ans[p] == 0):
        ans[p] = a[i];
    else:
        if (ans[p] == a[i]):
            print(a[i],end=",");
        else:
            # Hashing collision happened increment
            # position and do recursive call
            p = p + 1;
            placeValue(a, ans, i, p, v);
 
# Driver code
a = [ 7, 1, 5, 2, 3, 6 ];
b = [ 3, 8, 6, 20, 7 ];
findPosition(a, b);
 
# This code is contributed by mits

C#

// C# program to find union and intersection
// using similar Hashing Technique
// without using any predefined Java Collections
// Time Complexity best case & avg case = O(m+n)
// Worst case = O(nlogn)
 
//package com.arrays.math;
using System;
class UnsortedIntersectionUnion
{
 
        // Prints intersection of arr1[0..n1-1] and
        // arr2[0..n2-1]
    public void findPosition(int []a, int []b)
    {
        int v = (a.Length + b.Length);
        int []ans = new int[v];
 
        int zero1 = 0;
        int zero2 = 0;
 
        Console.Write("Intersection : ");
         
        // Iterate first array
        for (int i = 0; i < a.Length; i++)
            zero1 = iterateArray(a, v, ans, i);
 
        // Iterate second array
        for (int j = 0; j < b.Length; j++)
            zero2 = iterateArray(b, v, ans, j);
 
        int zero = zero1 + zero2;
        placeZeros(v, ans, zero);
        printUnion(v, ans, zero);
 
    }
     
    // Prints union of arr1[0..n1-1]
    // and arr2[0..n2-1]
    private void printUnion(int v, int[] ans, int zero)
    {
        int zero1 = 0;
        Console.Write("\nUnion : ");
        for (int i = 0; i < v; i++)
        {
            if ((zero == 0 && ans[i] == 0) ||
                    (ans[i] == 0 && zero1 > 0))
                continue;
            if (ans[i] == 0)
                zero1++;
            Console.Write(ans[i] + ",");
        }
    }
 
    private void placeZeros(int v, int[] ans, int zero)
    {
        if (zero == 2)
        {
            Console.WriteLine("0");
            int []d = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
        if (zero == 1)
        {
            int []d = { 0 };
            placeValue(d, ans, 0, 0, v);
        }
    }
 
    // Function to itreate array
    private int iterateArray(int[] a, int v,
                            int[] ans, int i)
    {
        if (a[i] != 0)
        {
            int p = a[i] % v;
            placeValue(a, ans, i, p, v);
        } else
            return 1;
        return 0;
    }
 
    private void placeValue(int[] a, int[] ans,
                                int i, int p, int v)
    {
        p = p % v;
        if (ans[p] == 0)
            ans[p] = a[i];
        else {
            if (ans[p] == a[i])
                Console.Write(a[i] + ",");
            else
            {
                 
                //Hashing collision happened increment
                // position and do recursive call
                p = p + 1;
                placeValue(a, ans, i, p, v);
            }
        }
    }
 
    // Driver code
    public static void Main()
    {
        int []a = { 7, 1, 5, 2, 3, 6 };
        int []b = { 3, 8, 6, 20, 7 };
 
        UnsortedIntersectionUnion uiu = new UnsortedIntersectionUnion();
        uiu.findPosition(a, b);
    }
}
 
// This code is contributed by PrinciRaj1992
输出
Intersection : 3,6,7,
Union : 1,2,3,5,6,7,8,20,

Python3

#  Python program to find union and intersection
#  using sets
 
 
def printUnion(arr1, arr2, n1, n2):
    hs = set()
    #  Inhsert the elements of arr1[] to set hs
    for i in range(0, n1):
        hs.add(arr1[i])
    #  Inhsert the elements of arr1[] to set hs
    for i in range(0, n2):
        hs.add(arr2[i])
    print("Union:")
    for i in hs:
        print(i, end=" ")
    print("\n")
    #  Prints intersection of arr1[0..n1-1] and
    #  arr2[0..n2-1]
 
 
def printIntersection(arr1, arr2, n1, n2):
    hs = set()
    #  Insert the elements of arr1[] to set S
    for i in range(0, n1):
        hs.add(arr1[i])
    print("Intersection:")
    for i in range(0, n2):
        #  If element is present in set then
        #  push it to vector V
        if arr2[i] in hs:
            print(arr2[i], end=" ")
 
 
#  Driver Program
arr1 = [7, 1, 5, 2, 3, 6]
arr2 = [3, 8, 6, 20, 7]
n1 = len(arr1)
n2 = len(arr2)
 
# Function call
printUnion(arr1, arr2, n1, n2)
printIntersection(arr1, arr2, n1, n2)
 
# This artice is contributed by Kumar Suman .

有关排序数组,请参见以下文章。
查找两个排序数组的并集和交集