📌  相关文章
📜  来自两个给定数组的最大数组保持顺序相同

📅  最后修改于: 2021-10-27 08:04:40             🧑  作者: Mango

给定两个相同大小的数组 A[] 和 B[](两个数组分别包含不同的元素,但可能有一些共同的元素),任务是形成相同大小的第三个(或结果)数组。生成的数组应具有来自两个数组的最多 n 个元素。它应该首先选择 A[] 的元素,然后按照它们在原始数组中出现的相同顺序选择 B[] 的元素。如果有共同元素,那么 res[] 中应该只有一个元素,并且应该优先考虑 A[]。

例子:

Input :  A[] =  [ 9 7 2 3 6 ]
         B[] =  [ 7 4 8 0 1 ]
Output : res[] = [9 7 6 4 8]
res[] has maximum n elements of both A[] 
and B[] such that elements of A[] appear
first (in same order), then elements of B[].
Also 7 is common and priority is given to
A's 7.

Input :  A[] = [ 6 7 5 3 ]
         B[] = [ 5 6 2 9 ] 
Output : res[] = [ 6 7 5 9 ]

1) 创建两个数组的副本并按降序对副本进行排序。
2) 使用哈希选择两个数组中唯一的 n 个最大元素,优先考虑 A[]。
3) 将结果数组初始化为空。
4) 遍历 A[],复制 A[] 中存在于哈希中的那些元素。这样做是为了保持元素的顺序相同。
5) 对 B[] 重复步骤 4。这次我们只考虑那些不在 A[] 中的元素(不要在哈希中出现两次)。

下面是上述想法的实现。

C++
// Make a set of maximum elements from two
// arrays A[] and B[]
#include 
using namespace std;
 
void maximizeTheFirstArray(int A[], int B[],
                                    int n)
{
    // Create copies of A[] and B[] and sort
    // the copies in descending order.
    vector temp1(A, A+n);
    vector temp2(B, B+n);
    sort(temp1.begin(), temp1.end(), greater());
    sort(temp2.begin(), temp2.end(), greater());
 
    // Put maximum n distinct elements of
    // both sorted arrays in a map.
    unordered_map m;
    int i = 0, j = 0;
    while (m.size() < n)
    {
         if (temp1[i] >= temp2[j])
         {
            m[temp1[i]]++;
            i++;
         }
         else
         {
            m[temp2[j]]++;
            j++;
         }
    }
 
    // Copy elements of A[] to that
    // are present in hash m.
    vector res;
    for (int i = 0; i < n; i++)
        if (m.find(A[i]) != m.end())
           res.push_back(A[i]);
 
    // Copy elements of B[] to that
    // are present in hash m. This time
    // we also check if the element did
    // not appear twice.
    for (int i = 0; i < n; i++)
        if (m.find(B[i]) != m.end() &&
            m[B[i]] == 1)
           res.push_back(B[i]);
 
    // print result
    for (int i = 0; i < n; i++)
        cout << res[i] << " ";
}
 
// driver program
int main()
{
    int A[] = { 9, 7, 2, 3, 6 };
    int B[] = { 7, 4, 8, 0, 1 };
    int n = sizeof(A) / sizeof(A[0]);
    maximizeTheFirstArray(A, B, n);
    return 0;
}


Java
// Make a set of maximum elements from two
// arrays A[] and B[]
import java.io.*;
import java.util.*;
class GFG
{
     
    static void maximizeTheFirstArray(int[] A, int[] B,int n)
    {
       
        // Create copies of A[] and B[] and sort
        // the copies in descending order.
        ArrayList temp1 = new ArrayList();
        ArrayList temp2 = new ArrayList();
        for(int i : A)
        {
            temp1.add(i);
        }
        for(int i:B)
        {
            temp2.add(i);
        }
        Collections.sort(temp1, Collections.reverseOrder());
        Collections.sort(temp2, Collections.reverseOrder());
         
        // Put maximum n distinct elements of
        // both sorted arrays in a map.
        Map m = new HashMap<>();
        int i = 0, j = 0;
        while (m.size() < n)
        {
             if (temp1.get(i) >= temp2.get(j))
             {
                if(m.containsKey(temp1.get(i)))
                {
                    m.put(temp1.get(i), m.get(temp1.get(i)) + 1);
                }
                else
                {
                    m.put(temp1.get(i), 1);
                }
                i++;
             }
             else
             {
                if(m.containsKey(temp2.get(j)))
                {
                    m.put(temp2.get(j), m.get(temp2.get(j)) + 1);
                }
                else
                {
                    m.put(temp2.get(j), 1);
                }
                j++;
             }
        }
         
        // Copy elements of A[] to that
        // are present in hash m.
        ArrayList res = new ArrayList();
        for (i = 0; i < n; i++)
            if (m.containsKey(A[i]))
               res.add(A[i]);
      
        // Copy elements of B[] to that
        // are present in hash m. This time
        // we also check if the element did
        // not appear twice.
        for (i = 0; i < n; i++)
            if (m.containsKey(B[i]) && m.get(B[i]) == 1)
               res.add(B[i]);
      
        // print result
        for (i = 0; i < n; i++)
            System.out.print(res.get(i)+" ");
    }
      
    // Driver program   
    public static void main (String[] args)
    {
        int A[] = { 9, 7, 2, 3, 6 };
        int B[] = { 7, 4, 8, 0, 1 };
        int n = A.length;
        maximizeTheFirstArray(A, B, n);
    }
}
 
// This code is contributed by rag2127


Python3
# Python3 program to implement the
# above approach
# Make a set of maximum elements
# from two arrays A[] and B[]
from collections import defaultdict
 
def maximizeTheFirstArray(A, B, n):
 
    # Create copies of A[] and B[]
    # and sort the copies in
    # descending order.
    temp1 = A.copy()
    temp2 = B.copy()
    temp1.sort(reverse = True)
    temp2.sort(reverse = True)
 
    # Put maximum n distinct
    # elements of both sorted
    # arrays in a map.
    m = defaultdict(int)
    i = 0
    j = 0;
     
    while (len(m) < n):
         if (temp1[i] >= temp2[j]):
            m[temp1[i]] += 1
            i += 1       
         else:
            m[temp2[j]] += 1
            j += 1
 
    # Copy elements of A[] to that
    # are present in hash m.
    res = []
     
    for i in range (n):
        if (A[i] in m):
           res.append(A[i])
 
    # Copy elements of B[] to that
    # are present in hash m. This time
    # we also check if the element did
    # not appear twice.
    for i in range (n):
        if (B[i] in m and
            m[B[i]] == 1):
           res.append(B[i])
 
    # Print result
    for i in range (n):
        print (res[i], end = " ")
 
# Driver code
if __name__ == "__main__":
   
    A = [9, 7, 2, 3, 6]
    B = [7, 4, 8, 0, 1]
    n = len(A)
    maximizeTheFirstArray(A, B, n);
   
# This code is contributed by Chitranayal


C#
// Make a set of maximum elements from two
// arrays A[] and B[]
using System;
using System.Collections.Generic;
 
class GFG{
 
static void maximizeTheFirstArray(int[] A, int[] B,
                                  int n)
{
     
    // Create copies of A[] and B[] and sort
    // the copies in descending order.
    List temp1 = new List();
    List temp2 = new List();
     
    foreach(int i in A)
    {
        temp1.Add(i);
    }
     
    foreach(int i in B)
    {
        temp2.Add(i);
    }
     
    temp1.Sort();
    temp1.Reverse();
    temp2.Sort();
    temp2.Reverse();
      
    // Put maximum n distinct elements of
    // both sorted arrays in a map.
    Dictionary m = new Dictionary();
    int I = 0, j = 0;
    while (m.Count < n)
    {
        if (temp1[I] >= temp2[j])
        {
            if (m.ContainsKey(temp1[I]))
            {
                m[temp1[I]]++;
            }
            else
            {
                m.Add(temp1[I], 1);
            }
            I++;
        }
        else
        {
            if (m.ContainsKey(temp2[j]))
            {
                m[temp2[j]]++;
            }
            else
            {
                m.Add(temp2[j], 1);
            }
            j++;
        }
    }
 
    // Copy elements of A[] to that
    // are present in hash m.
    List res = new List();
    for(int i = 0; i < n; i++)
        if (m.ContainsKey(A[i]))
            res.Add(A[i]);
   
    // Copy elements of B[] to that
    // are present in hash m. This time
    // we also check if the element did
    // not appear twice.
    for(int i = 0; i < n; i++)
        if (m.ContainsKey(B[i]) && m[B[i]] == 1)
            res.Add(B[i]);
   
    // print result
    for(int i = 0; i < n; i++)
        Console.Write(res[i] + " ");
}
   
// Driver Code
static public void Main()
{
    int[] A = { 9, 7, 2, 3, 6 };
    int[] B = { 7, 4, 8, 0, 1 };
    int n = A.Length;
     
    maximizeTheFirstArray(A, B, n);
}
}
 
// This code is contributed by avanitrachhadiya2155


Javascript


输出:

9 7 6 4 8 

时间复杂度: O(n Log n)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程