📌  相关文章
📜  对由给定整数作为最后一个元素组成的子数组进行计数的查询

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

给定一个数组arr[]和一个由Q 个查询组成的数组query[] ,每个i查询的任务是计算以query[i]作为最后一个元素的子数组的数量。
注意:对于X 的不同出现,子数组将被认为是不同的

例子:

朴素方法:解决问题的最简单方法是为每个查询生成所有子数组,并且对于每个子数组,检查它是否包含X作为最后一个元素。
时间复杂度: O(Q×N 3 )
辅助空间: O(1)

高效的方法:为了优化上述方法,想法是使用Hashing。遍历数组,对于每个数组元素arr[i] ,搜索它在数组中的出现。对于每个索引,比如说idx ,在其中找到arr[i] ,将(idx+1)添加到将arr[i]作为最后一个元素的子数组的计数。

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

  • 初始化一个无序映射,比如mp,以存储以X作为最后一个元素的子数组的数量。
  • 遍历数组,对于每个整数arr[i] ,将mp[arr[i]]增加(i+1)。
  • 遍历数组query[]并为每个查询query[i]打印mp[query[i]]。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to perform queries to count the
// number of subarrays having given numbers
// as the last integer
int subarraysEndingWithX(
    int arr[], int N,
    int query[], int Q)
{
    // Stores the number of subarrays having
    // x as the last element
    unordered_map mp;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Stores current array element
        int val = arr[i];
 
        // Add contribution of subarrays
        // having arr[i] as last element
        mp[val] += (i + 1);
    }
 
    // Traverse the array of queries
    for (int i = 0; i < Q; i++) {
 
        int q = query[i];
 
        // Print the count of subarrays
        cout << mp[q] << " ";
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 5, 4, 5, 6 };
 
    // Number of queries
    int Q = 3;
 
    // Array of queries
    int query[] = { 1, 4, 5 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    subarraysEndingWithX(arr, N, query, Q);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to perform queries to count the
// number of subarrays having given numbers
// as the last integer
static void subarraysEndingWithX(
    int arr[], int N,
    int query[], int Q)
{
    // Stores the number of subarrays having
    // x as the last element
    HashMap mp = new HashMap();
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Stores current array element
        int val = arr[i];
 
        // Add contribution of subarrays
        // having arr[i] as last element
        if(mp.containsKey(val))
            mp.put(val, mp.get(val)+(i+1));
        else
            mp.put(val, i+1);
    }
 
    // Traverse the array of queries
    for (int i = 0; i < Q; i++) {
 
        int q = query[i];
 
        // Print the count of subarrays
        System.out.print(mp.get(q)+ " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array
    int arr[] = { 1, 5, 4, 5, 6 };
 
    // Number of queries
    int Q = 3;
 
    // Array of queries
    int query[] = { 1, 4, 5 };
 
    // Size of the array
    int N = arr.length;
 
    subarraysEndingWithX(arr, N, query, Q);
 
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python 3 program for the above approach
 
# Function to perform queries to count the
# number of subarrays having given numbers
# as the last integer
def subarraysEndingWithX(arr, N, query, Q):
   
    # Stores the number of subarrays having
    # x as the last element
    mp = {}
 
    # Traverse the array
    for i in range(N):
       
        # Stores current array element
        val = arr[i]
 
        # Add contribution of subarrays
        # having arr[i] as last element
        if val in mp:
            mp[val] += (i + 1)
        else:
            mp[val] = mp.get(val, 0) + (i + 1);
 
    # Traverse the array of queries
    for i in range(Q):
        q = query[i]
 
        # Print the count of subarrays
        print(mp[q],end = " ")
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    arr =  [1, 5, 4, 5, 6]
     
    # Number of queries
    Q = 3
     
    # Array of queries
    query  = [1, 4, 5]
     
    # Size of the array
    N = len(arr)
    subarraysEndingWithX(arr, N, query, Q)
     
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
    // Function to perform queries to count the
    // number of subarrays having given numbers
    // as the last integer
    static void subarraysEndingWithX(int[] arr, int N,
                                     int[] query, int Q)
    {
       
        // Stores the number of subarrays having
        // x as the last element
        Dictionary mp
            = new Dictionary();
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Stores current array element
            int val = arr[i];
 
            // Add contribution of subarrays
            // having arr[i] as last element
            if (mp.ContainsKey(val))
                mp[val] = mp[val] + (i + 1);
            else
                mp[val] = i + 1;
        }
 
        // Traverse the array of queries
        for (int i = 0; i < Q; i++)
        {
            int q = query[i];
 
            // Print the count of subarrays
            Console.Write(mp[q] + " ");
        }
    }
 
    // Driver Code
    public static void Main()
    {
       
        // Given array
        int[] arr = { 1, 5, 4, 5, 6 };
 
        // Number of queries
        int Q = 3;
 
        // Array of queries
        int[] query = { 1, 4, 5 };
 
        // Size of the array
        int N = arr.Length;
        subarraysEndingWithX(arr, N, query, Q);
    }
}
 
// This code is contributed by chitranayal.


Javascript


输出:
1 3 6

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

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