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

📅  最后修改于: 2021-09-06 11:32:00             🧑  作者: Mango

给定一个初始数组A[]和最终数组B[]两个大小为N 的数组都包含范围[1, N]中的整数,其中A[]表示插入元素的顺序, B[]表示在它们被删除,任务是找到B[] 中位于索引处的元素数量,该索引早于其在A[] 中的相应位置。

例子:

朴素的方法:解决这个问题最简单的方法是将B[]中每个元素的位置与A[]中所有其他元素的位置进行比较,并检查它是否插入在A[] 中的元素之后但在之前被移除乙[] 。如果是,则增加计数。最后,打印总计数。

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

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

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

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

下面是上述方法的实现:

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


Javascript


输出:
1

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live