📌  相关文章
📜  用给定元素替换索引 P 处的元素后打印不同数组元素计数的查询

📅  最后修改于: 2021-10-27 09:21:25             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[]和由形式为 { p , x } 的Q 个查询组成的二维数组查询 [][] ,每个查询的任务是用x替换位置p处的元素并打印计数数组中存在的不同元素。

例子:

朴素的方法:最简单的方法是为每个查询更新给定的数组,并将更新后的数组的所有元素插入到一个 Set 中。将集合的大小打印为不同数组元素的计数。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
#define R 3
#define C 2
 
// Function to the total
// number of distinct elements
// after each query update
void Distinct(int arr[], int n,
              int p, int x)
{
  // Update the array
  arr[p - 1] = x;
 
  // Store distinct elements
  set set;
  for (int i = 0; i < n; i++)
  {
    set.insert(arr[i]);
  }
 
  // Print the size
  cout << set.size() << " ";
}
 
// Function to print the count of
// distinct elements for each query
void updateArray(int arr[], int n,
                 int queries[R][C],
                 int q)
{
  // Traverse the query
  for (int i = 0; i < q; i++)
  {
    // Function Call to update
    // each query
    Distinct(arr, n,
             queries[i][0],
             queries[i][1]);
  }
}
 
// Driver Code
int main()
{
  // Given array arr[]
  int arr[] = {2, 2, 5,
               5, 4, 6, 3};
 
  int N = sizeof(arr) /
          sizeof(arr[0]);
 
  int Q = 3;
 
  // Given queries
  int queries[R][C] = {{1, 7},
                       {6, 8},
                       {7, 2}};
 
  // Function Call
  updateArray(arr, N,
              queries, Q);
}
 
// This code is contributed by gauravrajput1


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to the total number
    // of distinct elements after each
    // query update
    static void Distinct(int arr[], int n,
                         int p, int x)
    {
        // Update the array
        arr[p - 1] = x;
 
        // Store distinct elements
        Set set = new HashSet<>();
 
        for (int i = 0; i < n; i++) {
            set.add(arr[i]);
        }
 
        // Print the size
        System.out.print(set.size() + " ");
    }
 
    // Function to print the count of
    // distinct elements for each query
    static void updateArray(
        int arr[], int n,
        int queries[][], int q)
    {
        // Traverse the query
        for (int i = 0; i < q; i++) {
 
            // Function Call to update
            // each query
            Distinct(arr, n, queries[i][0],
                     queries[i][1]);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 2, 2, 5, 5, 4, 6, 3 };
 
        int N = arr.length;
 
        int Q = 3;
 
        // Given queries
        int queries[][]
            = new int[][] { { 1, 7 },
                            { 6, 8 },
                            { 7, 2 } };
 
        // Function Call
        updateArray(arr, N, queries, Q);
    }
}


Python3
# Python3 program for the
# above approach
 
# Function to the total number
# of distinct elements after
# each query update
def Distinct(arr, n, p, x):
   
    # Update the array
    arr[p - 1] = x;
 
    # Store distinct elements
    s = set();
 
 
    for i in range(n):
        s.add(arr[i]);
 
    # Prthe size
    print(len(s), end = " ");
 
# Function to print count
# of distinct elements for
# each query
def updateArray(arr, n,
                queries, q):
   
    # Traverse the query
    for i in range(0, q):
       
        # Function Call to update
        # each query
        Distinct(arr, n,
                 queries[i][0],
                 queries[i][1]);
 
# Driver Code
if __name__ == '__main__':
   
    # Given array arr
    arr = [2, 2, 5,
           5, 4, 6, 3];
 
    N = len(arr);
    Q = 3;
 
    # Given queries
    queries = [[1, 7],
               [6, 8],
               [7, 2]];
 
    # Function Call
    updateArray(arr, N, queries, Q);
 
# This code is contributed by shikhasingrajput


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to the total number
// of distinct elements after each
// query update
static void Distinct(int []arr, int n,
                     int p, int x)
{
  // Update the array
  arr[p - 1] = x;
 
  // Store distinct elements
  HashSet set =
          new HashSet();
 
  for (int i = 0; i < n; i++)
  {
    set.Add(arr[i]);
  }
 
  // Print the size
  Console.Write(set.Count + " ");
}
 
// Function to print the count of
// distinct elements for each query
static void updateArray(int []arr, int n,
                        int [,]queries, int q)
{
  // Traverse the query
  for (int i = 0; i < q; i++)
  {
    // Function Call to update
    // each query
    Distinct(arr, n, queries[i, 0],
             queries[i, 1]);
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int[] arr = {2, 2, 5, 5,
               4, 6, 3};
 
  int N = arr.Length;
  int Q = 3;
 
  // Given queries
  int [,]queries = new int[,] {{1, 7},
                               {6, 8},
                               {7, 2}};
 
  // Function Call
  updateArray(arr, N, queries, Q);
}
}
 
// This code is contributed by gauravrajput1


Javascript


C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
#define Q 3
// Function to store the frequency
// of each element in the Map
void store(int arr[], int n,
           map &map)
{
  for (int i = 0; i < n; i++)
  {
    // Store the frequency of
    // element arr[i]
    map[arr[i]]++;
  }
}
 
// Function to update an array
// and map & to find the
// distinct elements
void Distinct(int arr[], int n,
              int p, int x,
              map &map)
{
  // Decrease the element
  // if it was previously
  // present in Map
  map[arr[p - 1]] =
          map[arr[p - 1]] - 1;
 
  if (map[arr[p - 1]] == 0)
    map.erase(arr[p - 1]);
 
  // Add the new element
  // to map
  map[x]++;
 
  // Update the array
  arr[p - 1] = x;
   
  // Print the count of
  // distinct elements
  cout << (map.size()) << " ";
}
 
// Function to count the distinct
// element after updating each query
static void updateQuery(int arr[], int n,
                        int queries[Q][2],
                        int q)
{
  // Store the elements in map
  map map;
 
  store(arr, n, map);
 
  for (int i = 0; i < q; i++)
  {
    // Function Call
    Distinct(arr, n,
             queries[i][0],
             queries[i][1], map);
  }
}
 
// Driver Code
int main()
{
  // Given array arr[]
  int arr[] = {2, 2, 5,
               5, 4, 6, 3};
 
  int N = sizeof(arr) /
          sizeof(arr[0]);
 
  // Given Queries
  int queries[Q][2] = {{1, 7},
                       {6, 8},
                       {7, 2}};
 
  // Function Call
  updateQuery(arr, N, queries, Q);
}
 
// This code is contributed by gauravrajput1


Java
// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to store the frequency
    // of each element in the Map
    static void store(int arr[], int n,
                      HashMap
                          map)
    {
        for (int i = 0; i < n; i++) {
 
            // Store the frequency of
            // element arr[i]
            if (!map.containsKey(arr[i]))
                map.put(arr[i], 1);
            else
                map.put(arr[i],
                        map.get(arr[i]) + 1);
        }
    }
 
    // Function to update an array and
    // map & to find the distinct elements
    static void Distinct(int arr[], int n,
                         int p, int x,
                         HashMap
                             map)
    {
 
        // Decrease the element if it
        // was previously present in Map
        map.put(arr[p - 1],
                map.get(arr[p - 1]) - 1);
 
        if (map.get(arr[p - 1]) == 0)
            map.remove(arr[p - 1]);
 
        // Add the new element to map
        if (!map.containsKey(x)) {
            map.put(x, 1);
        }
        else {
            map.put(x, map.get(x) + 1);
        }
 
        // Update the array
        arr[p - 1] = x;
 
        // Print the count of distinct
        // elements
        System.out.print(map.size() + " ");
    }
 
    // Function to count the distinct
    // element after updating each query
    static void updateQuery(
        int arr[], int n,
        int queries[][], int q)
    {
        // Store the elements in map
        HashMap map
            = new HashMap<>();
 
        store(arr, n, map);
 
        for (int i = 0; i < q; i++) {
 
            // Function Call
            Distinct(arr, n, queries[i][0],
                     queries[i][1], map);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 2, 2, 5, 5, 4, 6, 3 };
 
        int N = arr.length;
        int Q = 3;
 
        // Given Queries
        int queries[][]
            = new int[][] { { 1, 7 },
                            { 6, 8 },
                            { 7, 2 } };
 
        // Function Call
        updateQuery(arr, N, queries, Q);
    }
}


Python3
# Python3 Program to implement
# the above approach
 
# Function to store the frequency
# of each element in the Map
def store(arr, n, Map) :
    for i in range(n) :
          
        # Store the frequency of
        # element arr[i]
        if (arr[i] not in Map) :
            Map[arr[i]] = 1
        else :
            Map[arr[i]] += 1
             
# Function to update an array and
# map & to find the distinct elements
def Distinct(arr, n, p, x, Map) :
      
    # Decrease the element if it
    # was previously present in Map
    Map[arr[p - 1]] = Map[arr[p - 1]] - 1
  
    if (Map[arr[p - 1]] == 0) :
        del Map[arr[p - 1]]
  
    # Add the new element to map
    if(x not in Map) :
     
        Map[x] = 1
     
    else :
     
        Map[x] += 1
      
    # Update the array
    arr[p - 1] = x
  
    # Print the count of distinct
    # elements
    print(len(Map), end = " ")
     
# Function to count the distinct
# element after updating each query
def updateQuery(arr, n, queries, q) :
      
    # Store the elements in map
    Map = {}
  
    store(arr, n, Map)
  
    for i in range(q) :
          
        # Function Call
        Distinct(arr, n, queries[i][0], queries[i][1], Map)
 
# Given array []arr
arr = [ 2, 2, 5, 5, 4, 6, 3 ]
 
N = len(arr)
Q = 3
 
# Given queries
queries = [ [ 1, 7 ], [ 6, 8 ], [ 7, 2 ] ]
 
# Function call
updateQuery(arr, N, queries, Q)
 
# This code is contributed by divyesh072019.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to store the frequency
// of each element in the Map
static void store(int []arr, int n,
       Dictionarymap)
{
    for(int i = 0; i < n; i++)
    {
         
        // Store the frequency of
        // element arr[i]
        if (!map.ContainsKey(arr[i]))
            map.Add(arr[i], 1);
        else
            map[arr[i]] = map[arr[i]] + 1;
    }
}
 
// Function to update an array and
// map & to find the distinct elements
static void Distinct(int []arr, int n,
                     int p, int x,
                     Dictionarymap)
{
     
    // Decrease the element if it
    // was previously present in Map
    map[arr[p - 1]] = map[arr[p - 1]] - 1;
 
    if (map[arr[p - 1]] == 0)
        map.Remove(arr[p - 1]);
 
    // Add the new element to map
    if (!map.ContainsKey(x))
    {
        map.Add(x, 1);
    }
    else
    {
        map[x]= map[x] + 1;
    }
     
    // Update the array
    arr[p - 1] = x;
 
    // Print the count of distinct
    // elements
    Console.Write(map.Count + " ");
}
 
// Function to count the distinct
// element after updating each query
static void updateQuery(int []arr, int n,
                        int [,]queries, int q)
{
     
    // Store the elements in map
    Dictionary map = new Dictionary();
 
    store(arr, n, map);
 
    for(int i = 0; i < q; i++)
    {
         
        // Function Call
        Distinct(arr, n, queries[i, 0],
                 queries[i, 1], map);
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int[] arr = { 2, 2, 5, 5, 4, 6, 3 };
 
    int N = arr.Length;
    int Q = 3;
 
    // Given queries
    int [,]queries = new int[,]{ { 1, 7 },
                                 { 6, 8 },
                                 { 7, 2 } };
 
    // Function call
    updateQuery(arr, N, queries, Q);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出
6 6 5 

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

高效的做法:对上述做法进行优化,思路是将每个数组元素出现的频率存储在一个Map中,然后遍历每个查询,每次更新后打印map的大小。请按照以下步骤解决问题:

  • 将每个元素的频率存储在 Map M 中
  • 对于每个查询{p, x} ,执行以下步骤:
    • Map M中将arr[p]的频率降低1 。如果其频率降低到0 ,则从Map 中删除该元素
    • 更新arr[p] = x并在地图中将x的频率增加1 (如果它已经存在)。否则,在Map 中添加元素x将其频率设置为1
  • 对于上述步骤中的每个查询,将Map的大小打印为不同数组元素的计数。

下面是上述方法的实现:

C++

// C++ Program to implement
// the above approach
#include 
using namespace std;
 
#define Q 3
// Function to store the frequency
// of each element in the Map
void store(int arr[], int n,
           map &map)
{
  for (int i = 0; i < n; i++)
  {
    // Store the frequency of
    // element arr[i]
    map[arr[i]]++;
  }
}
 
// Function to update an array
// and map & to find the
// distinct elements
void Distinct(int arr[], int n,
              int p, int x,
              map &map)
{
  // Decrease the element
  // if it was previously
  // present in Map
  map[arr[p - 1]] =
          map[arr[p - 1]] - 1;
 
  if (map[arr[p - 1]] == 0)
    map.erase(arr[p - 1]);
 
  // Add the new element
  // to map
  map[x]++;
 
  // Update the array
  arr[p - 1] = x;
   
  // Print the count of
  // distinct elements
  cout << (map.size()) << " ";
}
 
// Function to count the distinct
// element after updating each query
static void updateQuery(int arr[], int n,
                        int queries[Q][2],
                        int q)
{
  // Store the elements in map
  map map;
 
  store(arr, n, map);
 
  for (int i = 0; i < q; i++)
  {
    // Function Call
    Distinct(arr, n,
             queries[i][0],
             queries[i][1], map);
  }
}
 
// Driver Code
int main()
{
  // Given array arr[]
  int arr[] = {2, 2, 5,
               5, 4, 6, 3};
 
  int N = sizeof(arr) /
          sizeof(arr[0]);
 
  // Given Queries
  int queries[Q][2] = {{1, 7},
                       {6, 8},
                       {7, 2}};
 
  // Function Call
  updateQuery(arr, N, queries, Q);
}
 
// This code is contributed by gauravrajput1

Java

// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to store the frequency
    // of each element in the Map
    static void store(int arr[], int n,
                      HashMap
                          map)
    {
        for (int i = 0; i < n; i++) {
 
            // Store the frequency of
            // element arr[i]
            if (!map.containsKey(arr[i]))
                map.put(arr[i], 1);
            else
                map.put(arr[i],
                        map.get(arr[i]) + 1);
        }
    }
 
    // Function to update an array and
    // map & to find the distinct elements
    static void Distinct(int arr[], int n,
                         int p, int x,
                         HashMap
                             map)
    {
 
        // Decrease the element if it
        // was previously present in Map
        map.put(arr[p - 1],
                map.get(arr[p - 1]) - 1);
 
        if (map.get(arr[p - 1]) == 0)
            map.remove(arr[p - 1]);
 
        // Add the new element to map
        if (!map.containsKey(x)) {
            map.put(x, 1);
        }
        else {
            map.put(x, map.get(x) + 1);
        }
 
        // Update the array
        arr[p - 1] = x;
 
        // Print the count of distinct
        // elements
        System.out.print(map.size() + " ");
    }
 
    // Function to count the distinct
    // element after updating each query
    static void updateQuery(
        int arr[], int n,
        int queries[][], int q)
    {
        // Store the elements in map
        HashMap map
            = new HashMap<>();
 
        store(arr, n, map);
 
        for (int i = 0; i < q; i++) {
 
            // Function Call
            Distinct(arr, n, queries[i][0],
                     queries[i][1], map);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 2, 2, 5, 5, 4, 6, 3 };
 
        int N = arr.length;
        int Q = 3;
 
        // Given Queries
        int queries[][]
            = new int[][] { { 1, 7 },
                            { 6, 8 },
                            { 7, 2 } };
 
        // Function Call
        updateQuery(arr, N, queries, Q);
    }
}

蟒蛇3

# Python3 Program to implement
# the above approach
 
# Function to store the frequency
# of each element in the Map
def store(arr, n, Map) :
    for i in range(n) :
          
        # Store the frequency of
        # element arr[i]
        if (arr[i] not in Map) :
            Map[arr[i]] = 1
        else :
            Map[arr[i]] += 1
             
# Function to update an array and
# map & to find the distinct elements
def Distinct(arr, n, p, x, Map) :
      
    # Decrease the element if it
    # was previously present in Map
    Map[arr[p - 1]] = Map[arr[p - 1]] - 1
  
    if (Map[arr[p - 1]] == 0) :
        del Map[arr[p - 1]]
  
    # Add the new element to map
    if(x not in Map) :
     
        Map[x] = 1
     
    else :
     
        Map[x] += 1
      
    # Update the array
    arr[p - 1] = x
  
    # Print the count of distinct
    # elements
    print(len(Map), end = " ")
     
# Function to count the distinct
# element after updating each query
def updateQuery(arr, n, queries, q) :
      
    # Store the elements in map
    Map = {}
  
    store(arr, n, Map)
  
    for i in range(q) :
          
        # Function Call
        Distinct(arr, n, queries[i][0], queries[i][1], Map)
 
# Given array []arr
arr = [ 2, 2, 5, 5, 4, 6, 3 ]
 
N = len(arr)
Q = 3
 
# Given queries
queries = [ [ 1, 7 ], [ 6, 8 ], [ 7, 2 ] ]
 
# Function call
updateQuery(arr, N, queries, Q)
 
# This code is contributed by divyesh072019.

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to store the frequency
// of each element in the Map
static void store(int []arr, int n,
       Dictionarymap)
{
    for(int i = 0; i < n; i++)
    {
         
        // Store the frequency of
        // element arr[i]
        if (!map.ContainsKey(arr[i]))
            map.Add(arr[i], 1);
        else
            map[arr[i]] = map[arr[i]] + 1;
    }
}
 
// Function to update an array and
// map & to find the distinct elements
static void Distinct(int []arr, int n,
                     int p, int x,
                     Dictionarymap)
{
     
    // Decrease the element if it
    // was previously present in Map
    map[arr[p - 1]] = map[arr[p - 1]] - 1;
 
    if (map[arr[p - 1]] == 0)
        map.Remove(arr[p - 1]);
 
    // Add the new element to map
    if (!map.ContainsKey(x))
    {
        map.Add(x, 1);
    }
    else
    {
        map[x]= map[x] + 1;
    }
     
    // Update the array
    arr[p - 1] = x;
 
    // Print the count of distinct
    // elements
    Console.Write(map.Count + " ");
}
 
// Function to count the distinct
// element after updating each query
static void updateQuery(int []arr, int n,
                        int [,]queries, int q)
{
     
    // Store the elements in map
    Dictionary map = new Dictionary();
 
    store(arr, n, map);
 
    for(int i = 0; i < q; i++)
    {
         
        // Function Call
        Distinct(arr, n, queries[i, 0],
                 queries[i, 1], map);
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int[] arr = { 2, 2, 5, 5, 4, 6, 3 };
 
    int N = arr.Length;
    int Q = 3;
 
    // Given queries
    int [,]queries = new int[,]{ { 1, 7 },
                                 { 6, 8 },
                                 { 7, 2 } };
 
    // Function call
    updateQuery(arr, N, queries, Q);
}
}
 
// This code is contributed by Amit Katiyar

Javascript


输出
6 6 5 

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

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