📌  相关文章
📜  检查两个未排序的数组(允许重复)是否具有相同的元素

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

检查两个未排序的数组(允许重复)是否具有相同的元素

给定两个未排序的数组,检查两个数组是否具有相同的元素集。

例子:

Input : A = {2, 5, 6, 8, 10, 2, 2}
        B = {2, 5, 5, 6, 8, 5, 6}
Output : No 

Input : A = {2, 5, 6, 8, 2, 10, 2}
        B = {2, 5, 6, 8, 2, 10, 2}
Output : Yes

Input : A = {2, 5, 8, 6, 10, 2, 2}
        B = {2, 5, 6, 8, 2, 10, 2}
Output : Yes

方法一(简单):
这个问题的一个简单解决方案是检查 A 的每个元素是否都存在于 B 中。但是如果 B 中存在元素的多个实例,这种方法将导致错误的答案。为了解决这个问题,我们标记了访问过的实例B[] 使用辅助数组visited[]。

C++
// C++ implementation of the above approach
#include 
using namespace std;
// Function to check if both arrays are same
bool areSameSet(vector A, vector B)
{
    int n = A.size();
    if (B.size() != n)
        return false;
 
    // visited array is used to handle duplicates
    vector visited(n, false);
 
    // each element of A is matched
    // against each element of B
    for (int i = 0; i < n; i++) {
 
        int j = 0;
        for (j = 0; j < n; j++)
        {
            if (A[i] == B[j] && visited[j] == false)
            {
                visited[j] = true;
                break;           
            }  
        }
 
        // If we could not find A[i] in B[]
        if (j == n)
            return false;  
        
    }
    return true;
}
 
// Driver code
int main()
{
    vector A, B;
    A.push_back(2);
    A.push_back(5);
    A.push_back(10);
    A.push_back(6);
    A.push_back(8);
    A.push_back(2);
    A.push_back(2);
 
    B.push_back(2);
    B.push_back(5);
    B.push_back(6);
    B.push_back(8);
    B.push_back(10);
    B.push_back(2);
    B.push_back(2);
 
    areSameSet(A, B)? cout << "Yes" : cout << "No";
}


Java
// Java implementation of the above approach
import java.util.*;
 
class GFG
{
 
    // Function to check if both arrays are same
    static boolean areSameSet(Vector A, Vector B)
    {
        int n = A.size();
        if (B.size() != n)
        {
            return false;
        }
 
        // visited array is used to handle duplicates
        Vector visited = new Vector();
        for (int i = 0; i < n; i++)
        {
            visited.add(i, Boolean.FALSE);
        }
         
        // each element of A is matched
        // against each element of B
        for (int i = 0; i < n; i++)
        {
 
            int j = 0;
            for (j = 0; j < n; j++)
            {
                if (A.get(i) == B.get(j) && visited.get(j) == false)
                {
                    visited.add(j, Boolean.TRUE);
                    break;
                }
            }
 
            // If we could not find A[i] in B[]
            if (j == n)
            {
                return false;
            }
 
        }
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        Vector A = new Vector<>();
        Vector B = new Vector<>();
        A.add(2);
        A.add(5);
        A.add(10);
        A.add(6);
        A.add(8);
        A.add(2);
        A.add(2);
 
        B.add(2);
        B.add(5);
        B.add(6);
        B.add(8);
        B.add(10);
        B.add(2);
        B.add(2);
 
        if (areSameSet(A, B))
        {
            System.out.println("Yes");
        }
        else
        {
            System.out.println("No");
        }
    }
}
 
/* This code contributed by PrinciRaj1992 */


Python3
# Python3 implementation of the above approach
 
# Function to check if both arrays are same
def areSameSet(A, B):
 
    n = len(A)
    if (len(B) != n):
        return False
 
    # visited array is used to handle duplicates
    visited = [False for i in range(n)]
 
    # each element of A is matched
    # against each element of B
    for i in range(n):
 
        j = 0
        for j in range(n):
            if (A[i] == B[j] and
                visited[j] == False):
                visited[j] = True
                break
 
        # If we could not find A[i] in B[]
        if (j == n):
            return False
 
    return True
 
# Driver code
A = []
B = []
A.append(2)
A.append(5)
A.append(10)
A.append(6)
A.append(8)
A.append(2)
A.append(2)
 
B.append(2)
B.append(5)
B.append(6)
B.append(8)
B.append(10)
B.append(2)
B.append(2)
 
if(areSameSet(A, B)):
    print("Yes")
else:
    print("No")
     
# This code is contributed
# by mohit kumar


C#
// C# implementation of the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to check if both arrays are same
    static Boolean areSameSet(List A, List B)
    {
        int n = A.Count;
        if (B.Count != n)
        {
            return false;
        }
 
        // visited array is used to handle duplicates
        List visited = new List();
        for (int i = 0; i < n; i++)
        {
            visited.Insert(i, false);
        }
         
        // each element of A is matched
        // against each element of B
        for (int i = 0; i < n; i++)
        {
 
            int j = 0;
            for (j = 0; j < n; j++)
            {
                if (A[i] == B[j] && visited[j] == false)
                {
                    visited.Insert(j, true);
                    break;
                }
            }
 
            // If we could not find A[i] in B[]
            if (j == n)
            {
                return false;
            }
 
        }
        return true;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        List A = new List();
        List B = new List();
        A.Add(2);
        A.Add(5);
        A.Add(10);
        A.Add(6);
        A.Add(8);
        A.Add(2);
        A.Add(2);
 
        B.Add(2);
        B.Add(5);
        B.Add(6);
        B.Add(8);
        B.Add(10);
        B.Add(2);
        B.Add(2);
 
        if (areSameSet(A, B))
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript


C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to check if both arrays are same
bool areSameSet(vector A, vector B)
{
    int n = A.size();
    if (B.size() != n)
        return false;
 
    sort(A.begin(), A.end());
    sort(B.begin(), B.end());
 
    // Compare corresponding elements
    for (int i = 0; i < n; i++)
        if (A[i] != B[i])
            return false;       
     
    return true;
}
 
int main()
{
    vector A, B;
    A.push_back(2);
    A.push_back(5);
    A.push_back(10);
    A.push_back(6);
    A.push_back(8);
    A.push_back(2);
    A.push_back(2);
 
    B.push_back(2);
    B.push_back(5);
    B.push_back(6);
    B.push_back(8);
    B.push_back(10);
    B.push_back(2);
    B.push_back(2);
 
    areSameSet(A, B)? cout << "Yes" : cout << "No";
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
    // Function to check if both arrays are same
    static boolean areSameSet(Vector A,
                                Vector B)
    {
        int n = A.size();
        if (B.size() != n)
        {
            return false;
        }
 
        Collections.sort(A);
        Collections.sort(B);
 
        // Compare corresponding elements
        for (int i = 0; i < n; i++)
        {
            if (A.get(i) != B.get(i))
            {
                return false;
            }
        }
 
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        Vector A = new Vector<>();
        Vector B = new Vector<>();
        A.add(2);
        A.add(5);
        A.add(10);
        A.add(6);
        A.add(8);
        A.add(2);
        A.add(2);
 
        B.add(2);
        B.add(5);
        B.add(6);
        B.add(8);
        B.add(10);
        B.add(2);
        B.add(2);
 
        if (areSameSet(A, B))
        {
            System.out.println("Yes");
        }
        else
        {
            System.out.println("No");
        }
    }
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation of the approach
 
# Function to check if
# both arrays are same
def areSameSet(A, B):
 
    n = len(A)
    if (len(B) != n):
        return False
 
    A.sort()
    B.sort()
 
    # Compare corresponding
    # elements
    for i in range (n):
        if (A[i] != B[i]):
            return False     
     
    return True
 
# Driver code
if __name__ == "__main__":
 
    A = []
    B = []
    A.append(2)
    A.append(5)
    A.append(10)
    A.append(6)
    A.append(8)
    A.append(2)
    A.append(2)
 
    B.append(2)
    B.append(5)
    B.append(6)
    B.append(8)
    B.append(10)
    B.append(2)
    B.append(2)
 
    if areSameSet(A, B):
         print ("Yes")
    else:
         print ("No")
 
# This code is contributed by Chitranayal


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to check if both arrays are same
    static Boolean areSameSet(List A,
                                List B)
    {
        int n = A.Count;
        if (B.Count!= n)
        {
            return false;
        }
 
        A.Sort();
        B.Sort();
 
        // Compare corresponding elements
        for (int i = 0; i < n; i++)
        {
            if (A[i] != B[i])
            {
                return false;
            }
        }
 
        return true;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        List A = new List();
        List B = new List();
        A.Add(2);
        A.Add(5);
        A.Add(10);
        A.Add(6);
        A.Add(8);
        A.Add(2);
        A.Add(2);
 
        B.Add(2);
        B.Add(5);
        B.Add(6);
        B.Add(8);
        B.Add(10);
        B.Add(2);
        B.Add(2);
 
        if (areSameSet(A, B))
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript


C++
// C++ program to implement Naive approach
// to remove duplicates
#include 
using namespace std;
 
bool areSameSet(vector A, vector B)
{
    int n = A.size();
    if (B.size() != n)
        return false;
 
    // Create a hash table to
    // number of instances
    unordered_map m;
 
    // for each element of A
    // increase it's instance by 1.
    for (int i = 0; i < n; i++)
        m[A[i]]++;
     
    // for each element of B
    // decrease it's instance by 1.
    for (int i = 0; i < n; i++)
        m[B[i]]--;
     
    // Iterate through map and check if
    // any entry is non-zero
    for (auto i : m)
        if (i.second != 0)
            return false;
     
    return true;
}
 
int main()
{
    vector A, B;
    A.push_back(2);
    A.push_back(5);
    A.push_back(10);
    A.push_back(6);
    A.push_back(8);
    A.push_back(2);
    A.push_back(2);
 
    B.push_back(2);
    B.push_back(5);
    B.push_back(6);
    B.push_back(8);
    B.push_back(10);
    B.push_back(2);
    B.push_back(2);
 
    areSameSet(A, B)? cout << "Yes" : cout << "No";
}


Java
// Java program to implement Naive approach
// to remove duplicates
import java.util.HashMap;
 
class GFG
{
static boolean areSameSet(int[] A, int[] B)
{
    int n = A.length;
 
    if (B.length != n)
        return false;
 
    // Create a hash table to
    // number of instances
    HashMap m = new HashMap<>();
 
    // for each element of A
    // increase it's instance by 1.
    for (int i = 0; i < n; i++)
        m.put(A[i], m.get(A[i]) == null ? 1 :
                    m.get(A[i]) + 1);
 
    // for each element of B
    // decrease it's instance by 1.
    for (int i = 0; i < n; i++)
        m.put(B[i], m.get(B[i]) - 1);
 
    // Iterate through map and check if
    // any entry is non-zero
    for (HashMap.Entry entry : m.entrySet())
        if (entry.getValue() != 0)
            return false;
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] A = { 2, 5, 10, 6, 8, 2, 2 };
    int[] B = { 2, 5, 6, 8, 10, 2, 2 };
 
    if (areSameSet(A, B))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by
// sanjeev2552


Python3
# Python3 program to implement Naive
# approach to remove duplicates
def areSameSet(A, B):
     
    n = len(A)
     
    if (len(B) != n):
        return False
     
    # Create a hash table to
    # number of instances
    m = {}
     
    # For each element of A
    # increase it's instance by 1.
    for i in range(n):
        if A[i] not in m:
            m[A[i]] = 1
        else:
            m[A[i]] += 1
             
    # For each element of B
    # decrease it's instance by 1.
    for i in range(n):
        if B[i] in m:
            m[B[i]] -= 1
 
    # Iterate through map and check if
    # any entry is non-zero
    for i in m:
        if (m[i] != 0):
            return False
             
    return True
 
# Driver Code
A = []
B = []
 
A.append(2)
A.append(5)
A.append(10)
A.append(6)
A.append(8)
A.append(2)
A.append(2)
 
B.append(2)
B.append(5)
B.append(6)
B.append(8)
B.append(10)
B.append(2)
B.append(2)
 
if (areSameSet(A, B)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by avanitrachhadiya2155


C#
// C# program to implement Naive approach
// to remove duplicates
using System;
using System.Collections.Generic;
 
class GFG
{
     
static bool areSameSet(int[] A, int[] B)
{
    int n = A.Length;
 
    if (B.Length != n)
        return false;
 
    // Create a hash table to
    // number of instances
    Dictionary m = new Dictionary();
 
    // for each element of A
    // increase it's instance by 1.
    for (int i = 0; i < n; i++)
        if(m.ContainsKey(A[i]))
                m[A[i]] = m[A[i]] + 1;
        else
            m.Add(A[i], 1);
 
 
    // for each element of B
    // decrease it's instance by 1.
    for (int i = 0; i < n; i++)
        if(m.ContainsKey(B[i]))
                m[B[i]] = m[B[i]] - 1;
 
 
    // Iterate through map and check if
    // any entry is non-zero
    foreach(KeyValuePair entry in m)
        if (entry.Value != 0)
            return false;
    return true;
}
 
// Driver Code
public static void Main(String[] args)
{
    int[] A = { 2, 5, 10, 6, 8, 2, 2 };
    int[] B = { 2, 5, 6, 8, 10, 2, 2 };
 
    if (areSameSet(A, B))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:

Yes

上述解的时间复杂度为 O(n^2)。



方法二(排序):
对两个数组进行排序并比较每个数组的对应元素。

C++

// C++ implementation of the approach
#include 
using namespace std;
 
// Function to check if both arrays are same
bool areSameSet(vector A, vector B)
{
    int n = A.size();
    if (B.size() != n)
        return false;
 
    sort(A.begin(), A.end());
    sort(B.begin(), B.end());
 
    // Compare corresponding elements
    for (int i = 0; i < n; i++)
        if (A[i] != B[i])
            return false;       
     
    return true;
}
 
int main()
{
    vector A, B;
    A.push_back(2);
    A.push_back(5);
    A.push_back(10);
    A.push_back(6);
    A.push_back(8);
    A.push_back(2);
    A.push_back(2);
 
    B.push_back(2);
    B.push_back(5);
    B.push_back(6);
    B.push_back(8);
    B.push_back(10);
    B.push_back(2);
    B.push_back(2);
 
    areSameSet(A, B)? cout << "Yes" : cout << "No";
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
    // Function to check if both arrays are same
    static boolean areSameSet(Vector A,
                                Vector B)
    {
        int n = A.size();
        if (B.size() != n)
        {
            return false;
        }
 
        Collections.sort(A);
        Collections.sort(B);
 
        // Compare corresponding elements
        for (int i = 0; i < n; i++)
        {
            if (A.get(i) != B.get(i))
            {
                return false;
            }
        }
 
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        Vector A = new Vector<>();
        Vector B = new Vector<>();
        A.add(2);
        A.add(5);
        A.add(10);
        A.add(6);
        A.add(8);
        A.add(2);
        A.add(2);
 
        B.add(2);
        B.add(5);
        B.add(6);
        B.add(8);
        B.add(10);
        B.add(2);
        B.add(2);
 
        if (areSameSet(A, B))
        {
            System.out.println("Yes");
        }
        else
        {
            System.out.println("No");
        }
    }
}
 
// This code is contributed by 29AjayKumar

蟒蛇3

# Python3 implementation of the approach
 
# Function to check if
# both arrays are same
def areSameSet(A, B):
 
    n = len(A)
    if (len(B) != n):
        return False
 
    A.sort()
    B.sort()
 
    # Compare corresponding
    # elements
    for i in range (n):
        if (A[i] != B[i]):
            return False     
     
    return True
 
# Driver code
if __name__ == "__main__":
 
    A = []
    B = []
    A.append(2)
    A.append(5)
    A.append(10)
    A.append(6)
    A.append(8)
    A.append(2)
    A.append(2)
 
    B.append(2)
    B.append(5)
    B.append(6)
    B.append(8)
    B.append(10)
    B.append(2)
    B.append(2)
 
    if areSameSet(A, B):
         print ("Yes")
    else:
         print ("No")
 
# This code is contributed by Chitranayal

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to check if both arrays are same
    static Boolean areSameSet(List A,
                                List B)
    {
        int n = A.Count;
        if (B.Count!= n)
        {
            return false;
        }
 
        A.Sort();
        B.Sort();
 
        // Compare corresponding elements
        for (int i = 0; i < n; i++)
        {
            if (A[i] != B[i])
            {
                return false;
            }
        }
 
        return true;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        List A = new List();
        List B = new List();
        A.Add(2);
        A.Add(5);
        A.Add(10);
        A.Add(6);
        A.Add(8);
        A.Add(2);
        A.Add(2);
 
        B.Add(2);
        B.Add(5);
        B.Add(6);
        B.Add(8);
        B.Add(10);
        B.Add(2);
        B.Add(2);
 
        if (areSameSet(A, B))
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}
 
/* This code contributed by PrinciRaj1992 */

Javascript


输出:

Yes

上述解决方案的时间复杂度为 O(n*log(n))。

方法 3(散列):
我们可以通过使用哈希表来降低上述问题的时间复杂度。首先,我们遍历 A 并在哈希表中标记 A 的每个元素的实例数。然后我们遍历 B 并减少哈希表中的相应值。如果最后哈希表的所有条目都为零,则答案为“是”,否则为“否”。

C++

// C++ program to implement Naive approach
// to remove duplicates
#include 
using namespace std;
 
bool areSameSet(vector A, vector B)
{
    int n = A.size();
    if (B.size() != n)
        return false;
 
    // Create a hash table to
    // number of instances
    unordered_map m;
 
    // for each element of A
    // increase it's instance by 1.
    for (int i = 0; i < n; i++)
        m[A[i]]++;
     
    // for each element of B
    // decrease it's instance by 1.
    for (int i = 0; i < n; i++)
        m[B[i]]--;
     
    // Iterate through map and check if
    // any entry is non-zero
    for (auto i : m)
        if (i.second != 0)
            return false;
     
    return true;
}
 
int main()
{
    vector A, B;
    A.push_back(2);
    A.push_back(5);
    A.push_back(10);
    A.push_back(6);
    A.push_back(8);
    A.push_back(2);
    A.push_back(2);
 
    B.push_back(2);
    B.push_back(5);
    B.push_back(6);
    B.push_back(8);
    B.push_back(10);
    B.push_back(2);
    B.push_back(2);
 
    areSameSet(A, B)? cout << "Yes" : cout << "No";
}

Java

// Java program to implement Naive approach
// to remove duplicates
import java.util.HashMap;
 
class GFG
{
static boolean areSameSet(int[] A, int[] B)
{
    int n = A.length;
 
    if (B.length != n)
        return false;
 
    // Create a hash table to
    // number of instances
    HashMap m = new HashMap<>();
 
    // for each element of A
    // increase it's instance by 1.
    for (int i = 0; i < n; i++)
        m.put(A[i], m.get(A[i]) == null ? 1 :
                    m.get(A[i]) + 1);
 
    // for each element of B
    // decrease it's instance by 1.
    for (int i = 0; i < n; i++)
        m.put(B[i], m.get(B[i]) - 1);
 
    // Iterate through map and check if
    // any entry is non-zero
    for (HashMap.Entry entry : m.entrySet())
        if (entry.getValue() != 0)
            return false;
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] A = { 2, 5, 10, 6, 8, 2, 2 };
    int[] B = { 2, 5, 6, 8, 10, 2, 2 };
 
    if (areSameSet(A, B))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by
// sanjeev2552

蟒蛇3

# Python3 program to implement Naive
# approach to remove duplicates
def areSameSet(A, B):
     
    n = len(A)
     
    if (len(B) != n):
        return False
     
    # Create a hash table to
    # number of instances
    m = {}
     
    # For each element of A
    # increase it's instance by 1.
    for i in range(n):
        if A[i] not in m:
            m[A[i]] = 1
        else:
            m[A[i]] += 1
             
    # For each element of B
    # decrease it's instance by 1.
    for i in range(n):
        if B[i] in m:
            m[B[i]] -= 1
 
    # Iterate through map and check if
    # any entry is non-zero
    for i in m:
        if (m[i] != 0):
            return False
             
    return True
 
# Driver Code
A = []
B = []
 
A.append(2)
A.append(5)
A.append(10)
A.append(6)
A.append(8)
A.append(2)
A.append(2)
 
B.append(2)
B.append(5)
B.append(6)
B.append(8)
B.append(10)
B.append(2)
B.append(2)
 
if (areSameSet(A, B)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by avanitrachhadiya2155

C#

// C# program to implement Naive approach
// to remove duplicates
using System;
using System.Collections.Generic;
 
class GFG
{
     
static bool areSameSet(int[] A, int[] B)
{
    int n = A.Length;
 
    if (B.Length != n)
        return false;
 
    // Create a hash table to
    // number of instances
    Dictionary m = new Dictionary();
 
    // for each element of A
    // increase it's instance by 1.
    for (int i = 0; i < n; i++)
        if(m.ContainsKey(A[i]))
                m[A[i]] = m[A[i]] + 1;
        else
            m.Add(A[i], 1);
 
 
    // for each element of B
    // decrease it's instance by 1.
    for (int i = 0; i < n; i++)
        if(m.ContainsKey(B[i]))
                m[B[i]] = m[B[i]] - 1;
 
 
    // Iterate through map and check if
    // any entry is non-zero
    foreach(KeyValuePair entry in m)
        if (entry.Value != 0)
            return false;
    return true;
}
 
// Driver Code
public static void Main(String[] args)
{
    int[] A = { 2, 5, 10, 6, 8, 2, 2 };
    int[] B = { 2, 5, 6, 8, 10, 2, 2 };
 
    if (areSameSet(A, B))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by PrinciRaj1992

Javascript


输出:

Yes