📌  相关文章
📜  查询以给定整数作为最后一个元素的子数组

📅  最后修改于: 2021-05-17 05:55:12             🧑  作者: Mango

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

例子:

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

高效方法:为了优化上述方法,我们的想法是使用哈希。遍历数组,并为每个数组元素arr [i]搜索其在数组中的出现。对于每一个索引,说IDX,在该常用3 [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.


输出:
1 3 6

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