Dada una array arr[] de tamaño N y Q consultas de la forma [A, B] , la tarea es encontrar todos los elementos únicos de la array que son repetitivos y sus valores se encuentran entre A y B (ambos inclusive) para cada una de las consultas Q.
Ejemplos:
Entrada: arr[] = { 1, 5, 1, 2, 3, 3, 4, 0, 0 }, Q = 2, consultas={ { 1, 3 }, { 0, 0 } }
Salida: {3, 1}, { 0 }
Explicación: Para la primera consulta, los elementos 1 y 3 se encuentran en el rango dado y ocurren más de una vez.
Para la segunda consulta, solo 0 se encuentra en el rango y es de naturaleza repetitiva.Entrada: arr[] = {1, 5, 1, 2, 3, 4, 0, 0}, Q = 1, consultas={ { 1, 2 } }
Salida: 1
Enfoque ingenuo: el enfoque básico para resolver este problema es usar bucles anidados . El bucle externo realiza un recorrido de todos los elementos, y el bucle interno realiza una verificación de si el elemento seleccionado por el bucle externo aparece en cualquier otro lugar. Luego, si aparece en otro lugar, verifique si se encuentra dentro del rango de [A, B] . Si es así, imprímelo.
Complejidad de Tiempo: O(Q * N 2 )
Espacio Auxiliar: O(1)
Enfoque eficiente: un enfoque eficiente se basa en la idea de un mapa hash para almacenar la frecuencia de todos los elementos. Siga los pasos que se mencionan a continuación:
- Recorra el mapa hash y verifique si la frecuencia de un elemento es mayor que 1.
- En caso afirmativo, compruebe si el elemento está presente en el rango de [A, B] o no.
- En caso afirmativo, imprímalo; de lo contrario, omita el elemento.
- Continúe con el procedimiento anterior hasta que se atraviesen todos los elementos del mapa hash .
A continuación se muestra la implementación del enfoque anterior.
C++
// C++ code for the above approach. #include <bits/stdc++.h> using namespace std; // Initializing hashmap to store // Frequency of elements unordered_map<int, int> freq; // Function to store frequency of elements in hash map void storeFrequency(int arr[], int n) { // Iterating the array for (int i = 0; i < n; i++) { freq[arr[i]]++; } } // Function to print elements void printElements(int a, int b) { // Traversing the hash map for (auto it = freq.begin(); it != freq.end(); it++) { // Checking 1st condition if frequency > 1, i.e, // Element is repetitive if ((it->second) > 1) { int value = it->first; // Checking 2nd condition if element // Is in range of a and b or not if (value >= a && value <= b) { // Printing the value cout << value << " "; } } } } // Function to find the elements // satisfying given condition for each query void findElements(int arr[], int N, int Q, vector<pair<int, int> >& queries) { storeFrequency(arr, N); for (int i = 0; i < Q; i++) { int A = queries[i].first; int B = queries[i].second; printElements(A, B); cout << endl; } } // Driver code int main() { int arr[] = { 1, 5, 1, 2, 3, 3, 4, 0, 0 }; // Size of array int N = sizeof(arr) / sizeof(arr[0]); int Q = 2; vector<pair<int, int> > queries = { { 1, 3 }, { 0, 0 } }; // Function call findElements(arr, N, Q, queries); return 0; }
Java
// Java code for the above approach. import java.util.*; class GFG{ // Initializing hashmap to store // Frequency of elements static HashMap<Integer,Integer> freq=new HashMap<Integer,Integer> (); // Function to store frequency of elements in hash map static void storeFrequency(int arr[], int n) { // Iterating the array for (int i = 0 ; i < n; i++){ if(freq.containsKey(arr[i])){ freq.put(arr[i], freq.get(arr[i])+1); } else{ freq.put(arr[i], 1); } } } // Function to print elements static void printElements(int a, int b) { // Traversing the hash map for (Map.Entry<Integer,Integer> it : freq.entrySet()) { // Checking 1st condition if frequency > 1, i.e, // Element is repetitive if ((it.getValue()) > 1) { int value = it.getKey(); // Checking 2nd condition if element // Is in range of a and b or not if (value >= a && value <= b) { // Printing the value System.out.print(value+ " "); } } } } // Function to find the elements // satisfying given condition for each query static void findElements(int arr[], int N, int Q, int[][] queries) { storeFrequency(arr, N); for (int i = 0; i < Q; i++) { int A = queries[i][0]; int B = queries[i][1]; printElements(A, B); System.out.println(); } } // Driver code public static void main(String[] args) { int arr[] = { 1, 5, 1, 2, 3, 3, 4, 0, 0 }; // Size of array int N = arr.length; int Q = 2; int [][]queries = { { 1, 3 }, { 0, 0 } }; // Function call findElements(arr, N, Q, queries); } } // This code contributed by shikhasingrajput
Python3
# Python 3 code for the above approach. from collections import defaultdict # Initializing hashmap to store # Frequency of elements freq = defaultdict(int) # Function to store frequency of elements in hash map def storeFrequency(arr, n): # Iterating the array for i in range(n): freq[arr[i]] += 1 # Function to print elements def printElements(a, b): # Traversing the hash map for it in freq: # Checking 1st condition if frequency > 1, i.e, # Element is repetitive # print("it = ",it) if ((freq[it]) > 1): value = it # Checking 2nd condition if element # Is in range of a and b or not if (value >= a and value <= b): # Printing the value print(value, end=" ") # Function to find the elements # satisfying given condition for each query def findElements(arr, N, Q, queries): storeFrequency(arr, N) for i in range(Q): A = queries[i][0] B = queries[i][1] printElements(A, B) print() # Driver code if __name__ == "__main__": arr = [1, 5, 1, 2, 3, 3, 4, 0, 0] # Size of array N = len(arr) Q = 2 queries = [[1, 3], [0, 0]] # Function call findElements(arr, N, Q, queries) # This code is contributed by ukasp.
C#
// C# code for the above approach. using System; using System.Collections.Generic; public class GFG{ // Initializing hashmap to store // Frequency of elements static Dictionary<int,int> freq=new Dictionary<int,int> (); // Function to store frequency of elements in hash map static void storeFrequency(int []arr, int n) { // Iterating the array for (int i = 0 ; i < n; i++){ if(freq.ContainsKey(arr[i])){ freq[arr[i]]= freq[arr[i]]+1; } else{ freq.Add(arr[i], 1); } } } // Function to print elements static void printElements(int a, int b) { // Traversing the hash map foreach (KeyValuePair<int,int> it in freq) { // Checking 1st condition if frequency > 1, i.e, // Element is repetitive if ((it.Value) > 1) { int value = it.Key; // Checking 2nd condition if element // Is in range of a and b or not if (value >= a && value <= b) { // Printing the value Console.Write(value+ " "); } } } } // Function to find the elements // satisfying given condition for each query static void findElements(int []arr, int N, int Q, int[,] queries) { storeFrequency(arr, N); for (int i = 0; i < Q; i++) { int A = queries[i,0]; int B = queries[i,1]; printElements(A, B); Console.WriteLine(); } } // Driver code public static void Main(String[] args) { int []arr = { 1, 5, 1, 2, 3, 3, 4, 0, 0 }; // Size of array int N = arr.Length; int Q = 2; int [,]queries = { { 1, 3 }, { 0, 0 } }; // Function call findElements(arr, N, Q, queries); } } // This code contributed by shikhasingrajput
Javascript
<script> // JavaScript code for the above approach. // Initializing hashmap to store // Frequency of elements let freq = new Map(); // Function to store frequency of elements in hash map function storeFrequency(arr,n) { // Iterating the array for (let i = 0; i < n; i++) { freq[arr[i]]++; } } // Function to print elements function printElements(a, b) { // Traversing the hash map for (let [key, val] of freq.values()) { // Checking 1st condition if frequency > 1, i.e, // Element is repetitive if (val > 1) { let value =key; // Checking 2nd condition if element // Is in range of a and b or not if (value >= a && value <= b) { // Printing the value document.write(value + " "); } } } } // Function to find the elements // satisfying given condition for each query function findElements(arr, N, Q, queries) { storeFrequency(arr, N); for (let i = 0; i < Q; i++) { let A = queries[i][0]; let B = queries[i][1]; printElements(A, B); document.write("<br>"); } } // Driver code let arr = [ 1, 5, 1, 2, 3, 3, 4, 0, 0 ]; // Size of array let N = arr.length; let Q = 2; let queries = [ [ 1, 3 ], [ 0, 0 ] ]; // Function call findElements(arr, N, Q, queries); // This code is contributed by satwik4409. </script>
3 1 0
Complejidad temporal: O(Q*N + N)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por ninja_hattori y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA