📜  删除顺序先于插入顺序的数组元素计数

📅  最后修改于: 2021-05-14 08:56:25             🧑  作者: Mango

给定一个初始数组A []和一个最终数组B [],它们的大小均为N,包含范围为[1,N]的整数,其中A []表示元素插入的顺序,而B []表示元素的插入顺序。将其删除后,任务是查找位于比其在A []中的相应位置早的索引处的B []中的元素数。
例子:

天真的方法:解决此问题的最简单方法是将B []中每个元素的位置与A []中其他每个元素的位置进行比较,并检查是否将其插入到A []中的元素之后,然后将其删除。 B [] 。如果是,则增加计数。最后,打印总数。

时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:解决此问题的更好方法是维护一个队列并将B []的元素插入此队列,并将所有元素插入无序集合。无序集合用于有效检查特定元素是否已处理。从队列中遍历A []和pop元素,直到当前元素A [i]出现在队列顶部,还不断增加计数并标记出现在队列顶部的元素为已处理。最后,总数将给出B []中已向前移动的元素数。

请按照以下步骤解决问题:

  • 维护一个Queue无序集,并在两者中存储数组B []的值。
  • 现在,遍历数组A []
  • 如果当前元素不存在于无序集中,则意味着它已被删除。
  • 初始化变量计数。如果在队列中未找到任何i元素,则从队列中删除A [i]之前队列中存在的所有元素,并且无序集合将继续增加count
  • 从队列和无序集中删除A [i]
  • 最后,打印总数

下面是上述方法的实现:

C++
// C++ Program to implement
// the above appraoch
#include 
using namespace std;
 
// Function returns maximum number
// of required elements
int maximumCount(int A[], int B[], int n)
{
 
    queue q;
    unordered_set s;
 
    // Insert the elements of array B
    // in the queue and set
    for (int i = 0; i < n; i++) {
 
        s.insert(B[i]);
        q.push(B[i]);
    }
 
    // Stores the answer
    int count = 0;
 
    for (int i = 0; i < n; i++) {
 
        // If A[i] is already processed
        if (s.find(A[i]) == s.end())
            continue;
 
        // Until we find A[i] in the queue
        while (!q.empty() && q.front() != A[i]) {
 
            // Remove elements from the queue
            s.erase(q.front());
            q.pop();
 
            // Increment the count
            count++;
        }
 
        // Remove the current element A[i]
        // from the queue and set.
        if (A[i] == q.front()) {
 
            q.pop();
            s.erase(A[i]);
        }
 
        if (q.empty())
            break;
    }
 
    // Return total count
    cout << count << endl;
}
 
// Driver Code
int main()
{
    int N = 4;
    int A[] = { 1, 2, 3, 4 };
    int B[] = { 1, 2, 4, 3 };
 
    maximumCount(A, B, N);
    return 0;
}


Java
// Java program to implement
// the above appraoch
import java.util.*;
 
class GFG{
 
// Function returns maximum number
// of required elements
static void maximumCount(int A[], int B[], int n)
{
    Queue q = new LinkedList<>();
    HashSet s = new HashSet<>();
 
    // Insert the elements of array B
    // in the queue and set
    for(int i = 0; i < n; i++)
    {
        s.add(B[i]);
        q.add(B[i]);
    }
 
    // Stores the answer
    int count = 0;
 
    for(int i = 0; i < n; i++)
    {
         
        // If A[i] is already processed
        if (!s.contains(A[i]))
            continue;
 
        // Until we find A[i] in the queue
        while (!q.isEmpty() && q.peek() != A[i])
        {
 
            // Remove elements from the queue
            s.remove(q.peek());
            q.remove();
 
            // Increment the count
            count++;
        }
 
        // Remove the current element A[i]
        // from the queue and set.
        if (A[i] == q.peek())
        {
            q.remove();
            s.remove(A[i]);
        }
         
        if (q.isEmpty())
            break;
    }
     
    // Return total count
    System.out.print(count + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 4;
    int A[] = { 1, 2, 3, 4 };
    int B[] = { 1, 2, 4, 3 };
 
    maximumCount(A, B, N);
}
}
 
// This code is contributed by princi singh


Python3
# Python3 Program to implement
# the above appraoch
import queue
 
# Function returns maximum number
# of required elements
def maximumCount(A, B, n):
 
    q = queue.Queue() 
    s = set()
 
    # Insert the elements of
    # array B in the queue
    # and set
    for i in range(n):
        s.add(B[i])
        q.put(B[i])
 
    # Stores the answer
    count = 0
 
    for i in range(n):
 
        # If A[i] is already
        # processed
        if (A[i] not in s):
            continue
 
        # Until we find A[i]
        # in the queue
        while (q.qsize() > 0 and
               q.queue[0] != A[i]):
 
            # Remove elements from
            # the queue
            s.remove(q.queue[0]);
            q.get()
 
            # Increment the count
            count += 1
 
        # Remove the current element A[i]
        # from the queue and set.
        if (A[i] == q.queue[0]):
            q.get()
            s.remove(A[i])
 
        if (q.qsize() == 0):
            break
 
    # Return total count
    print(count)
     
# Driver code
N = 4
A = [1, 2, 3, 4]
B = [1, 2, 4, 3]
maximumCount(A, B, N)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program to implement
// the above appraoch
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function returns maximum number
// of required elements
static void maximumCount(int []A, int []B, int n)
{
    Queue q = new Queue();
    HashSet s = new HashSet();
 
    // Insert the elements of array B
    // in the queue and set
    for(int i = 0; i < n; i++)
    {
        s.Add(B[i]);
        q.Enqueue(B[i]);
    }
 
    // Stores the answer
    int count = 0;
 
    for(int i = 0; i < n; i++)
    {
         
        // If A[i] is already processed
        if (!s.Contains(A[i]))
            continue;
 
        // Until we find A[i] in the queue
        while (q.Count != 0 && q.Peek() != A[i])
        {
 
            // Remove elements from the queue
            s.Remove(q.Peek());
            q.Dequeue();
 
            // Increment the count
            count++;
        }
 
        // Remove the current element A[i]
        // from the queue and set.
        if (A[i] == q.Peek())
        {
            q.Dequeue();
            s.Remove(A[i]);
        }
        if (q.Count == 0)
            break;
    }
     
    // Return total count
    Console.Write(count + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 4;
    int []A = { 1, 2, 3, 4 };
    int []B = { 1, 2, 4, 3 };
 
    maximumCount(A, B, N);
}
}
 
// This code is contributed by princi singh


输出:
1

时间复杂度: O(N)
辅助空间: O(N)