Dada una array de tamaño n, el objetivo es encontrar el número más pequeño que se repite exactamente ‘k’ veces donde k > 0?
Suponga que la array solo tiene números enteros positivos y 1 <= arr[i] < 1000 para cada i = 0 a n -1.
Ejemplos:
Input : arr[] = {2 2 1 3 1} k = 2 Output: 1 Explanation: Here in array, 2 is repeated 2 times 1 is repeated 2 times 3 is repeated 1 time Hence 2 and 1 both are repeated 'k' times i.e 2 and min(2, 1) is 1 Input : arr[] = {3 5 3 2} k = 1 Output : 2 Explanation: Both 2 and 5 are repeating 1 time but min(5, 2) is 2
Enfoque simple: un enfoque simple es usar dos bucles anidados. El bucle exterior elige un elemento uno por uno comenzando desde el elemento más a la izquierda. El bucle interno verifica si el mismo elemento está presente en el lado derecho. Si está presente, aumente el conteo y haga negativo el número que obtuvimos en el lado derecho para evitar que cuente nuevamente.
Implementación:
C++
// C++ program to find smallest number // in array that is repeated exactly // 'k' times. #include <bits/stdc++.h> using namespace std; const int MAX = 1000; int findDuplicate(int arr[], int n, int k) { // Since arr[] has numbers in range from // 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number is present // once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is equal to 'k' if (count == k) res = min(res, arr[i]); } } return res; } // Driver code int main() { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0; }
Java
// Java program to find smallest number // in array that is repeated exactly // 'k' times. public class GFG { static final int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Since arr[] has numbers in range from // 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number is // present once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is equal // to 'k' if (count == k) res = Math.min(res, arr[i]); } } return res; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); } } // This article is contributed by Sumit Ghosh
Python3
# Python 3 program to find smallest # number in array that is repeated # exactly 'k' times. MAX = 1000 def findDuplicate(arr, n, k): # Since arr[] has numbers in # range from 1 to MAX res = MAX + 1 for i in range(0, n): if (arr[i] > 0): # set count to 1 as number # is present once count = 1 for j in range(i + 1, n): if (arr[i] == arr[j]): count += 1 # If frequency of number is equal to 'k' if (count == k): res = min(res, arr[i]) return res # Driver code arr = [2, 2, 1, 3, 1] k = 2 n = len(arr) print(findDuplicate(arr, n, k)) # This code is contributed by Smitha Dinesh Semwal.
C#
// C# program to find smallest number // in array that is repeated exactly // 'k' times. using System; public class GFG { static int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Since arr[] has numbers in range // from 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number // is present once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is // equal to 'k' if (count == k) res = Math.Min(res, arr[i]); } } return res; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); } } // This article is contributed by vt_m.
PHP
<?php // PHP program to find smallest number // in array that is repeated exactly // 'k' times. function findDuplicate($arr, $n, $k) { // Since arr[] has numbers in // range from 1 to MAX $MAX = 1000; $res = $MAX + 1; for ($i = 0; $i < $n; $i++) { if ($arr[$i] > 0) { // set count to 1 as number is // present once $count = 1; for ($j = $i + 1; $j < $n; $j++) if ($arr[$i] == $arr[$j]) $count += 1; // If frequency of number is // equal to 'k' if ($count == $k) $res = min($res, $arr[$i]); } } return $res; } // Driver code $arr = array(2, 2, 1, 3, 1); $k = 2; $n = count($arr); echo findDuplicate($arr, $n, $k); // This code is contributed by Rajput-Ji ?>
Javascript
<script> // Javascript program to find smallest number // in array that is repeated exactly // 'k' times let MAX = 1000; // finds the smallest number in arr[] // that is repeated k times function findDuplicate(arr, n, k) { // Computing frequencies of all elements let freq = new Array(MAX).fill(0); for (let i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { document.write("Out of range"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (let i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1; } // driver program let arr = [ 2, 2, 1, 3, 1 ]; let k = 2; let n = arr.length; document.write(findDuplicate(arr, n, k)); // This code is contributed by code_hunt. </script>
1
Complejidad de Tiempo : O(n 2 )
Espacio Auxiliar : O(1)
Esta solución no requiere que los elementos de la array estén en un rango limitado.
Mejor solución : ordene la array de entrada y encuentre el primer elemento con exactamente k recuento de apariciones.
Implementación:
C++
// C++ program to find smallest number // in array that is repeated exactly // 'k' times. #include <bits/stdc++.h> using namespace std; int findDuplicate(int arr[], int n, int k) { // Sort the array sort(arr, arr + n); // Find the first element with exactly // k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } // Driver code int main() { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0; }
Java
// Java program to find smallest number // in array that is repeated exactly // 'k' times. import java.util.Arrays; public class GFG { // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Sort the array Arrays.sort(arr); // Find the first element with exactly // k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); } } // This article is contributed by Sumit Ghosh
Python3
# Python program to find smallest number # in array that is repeated exactly # 'k' times. def findDuplicate(arr, n, k): # Sort the array arr.sort() # Find the first element with exactly # k occurrences. i = 0 while (i < n): j, count = i + 1, 1 while (j < n and arr[j] == arr[i]): count += 1 j += 1 if (count == k): return arr[i] i = j return -1 # Driver code arr = [ 2, 2, 1, 3, 1 ]; k = 2 n = len(arr) print(findDuplicate(arr, n, k)) # This code is contributed by Sachin Bisht
C#
// C# program to find smallest number // in array that is repeated exactly // 'k' times. using System; public class GFG { // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Sort the array Array.Sort(arr); // Find the first element with // exactly k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); } } // This article is contributed by vt_m.
PHP
<?php // PHP program to find smallest number // in array that is repeated exactly // 'k' times. // finds the smallest number in arr[] // that is repeated k times function findDuplicate($arr, $n, $k) { // Sort the array sort($arr); // Find the first element with // exactly k occurrences. $i = 0; while ($i < $n) { $j; $count = 1; for ($j = $i + 1; $j < $n && $arr[$j] == $arr[$i]; $j++) $count++; if ($count == $k) return $arr[$i]; $i = $j; } return -1; } // Driver code $arr = array( 2, 2, 1, 3, 1 ); $k = 2; $n = sizeof($arr); echo(findDuplicate($arr, $n, $k)); // This code is contributed // by Code_Mech. ?>
Javascript
<script> // JavaScript program to find smallest number // in array that is repeated exactly // 'k' times. // finds the smallest number in arr[] // that is repeated k times function findDuplicate(arr, n, k) { // Sort the array arr.sort(); // Find the first element with // exactly k occurrences. let i = 0; while (i < n) { let j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } let arr = [ 2, 2, 1, 3, 1 ]; let k = 2; let n = arr.length; document.write(findDuplicate(arr, n, k)); </script>
1
Complejidad de Tiempo : O(n Log n)
Espacio Auxiliar : O(1)
Enfoque eficiente: el enfoque eficiente se basa en el hecho de que la array tiene números en un rango pequeño (1 a 1000). Resolvemos este problema usando una array de frecuencias de tamaño máximo y almacenamos la frecuencia de cada número en esa array.
Implementación:
C++
// C++ program to find smallest number // in array that is repeated exactly // 'k' times. #include <bits/stdc++.h> using namespace std; const int MAX = 1000; int findDuplicate(int arr[], int n, int k) { // Computing frequencies of all elements int freq[MAX]; memset(freq, 0, sizeof(freq)); for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { cout << "Out of range"; return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1; } // Driver code int main() { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0; }
Java
// Java program to find smallest number // in array that is repeated exactly // 'k' times. public class GFG { static final int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Computing frequencies of all elements int[] freq = new int[MAX]; for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { System.out.println("Out of range"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); } } // This article is contributed by Sumit Ghosh
Python3
# Python program to find smallest number # in array that is repeated exactly # 'k' times. MAX = 1000 def findDuplicate(arr, n, k): # Computing frequencies of all elements freq = [0 for i in range(MAX)] for i in range(n): if (arr[i] < 1 and arr[i] > MAX): print("Out of range") return -1 freq[arr[i]] += 1 # Finding the smallest element with # frequency as k for i in range(MAX): # If frequency of any of the number # is equal to k starting from 0 # then return the number if (freq[i] == k): return i return -1 # Driver code arr = [ 2, 2, 1, 3, 1 ] k = 2 n = len(arr) print(findDuplicate(arr, n, k)) # This code is contributed by Sachin Bisht
C#
// C# program to find smallest number // in array that is repeated exactly // 'k' times. using System; public class GFG { static int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Computing frequencies of all // elements int[] freq = new int[MAX]; for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { Console.WriteLine("Out of range"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the // number is equal to k starting // from 0 then return the number if (freq[i] == k) return i; } return -1; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); } } // This article is contributed by vt_m.
PHP
<?php // PHP program to find smallest number // in array that is repeated exactly // 'k' times. $MAX = 1000; function findDuplicate($arr, $n, $k) { global $MAX; // Computing frequencies of all elements $freq=array_fill(0, $MAX, 0); for ($i = 0; $i < $n; $i++) { if ($arr[$i] < 1 && $arr[$i] > $MAX) { echo "Out of range"; return -1; } $freq[$arr[$i]] += 1; } // Finding the smallest element with // frequency as k for ($i = 0; $i < $MAX; $i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if ($freq[$i] == $k) return $i; } return -1; } // Driver code $arr = array( 2, 2, 1, 3, 1 ); $k = 2; $n = count($arr); echo findDuplicate($arr, $n, $k); // This code is contributed by mits ?>
Javascript
<script> // javascript program to find smallest number // in array that is repeated exactly // 'k' times. var MAX = 1000; // finds the smallest number in arr // that is repeated k times function findDuplicate(arr , n , k) { // Computing frequencies of all elements var freq = Array.from({length: MAX}, (_, i) => 0); for (var i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { document.write("Out of range"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (var i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1; } // Driver code var arr = [ 2, 2, 1, 3, 1 ]; var k = 2; var n = arr.length; document.write(findDuplicate(arr, n, k)); // This code is contributed by 29AjayKumar </script>
1
Complejidad temporal: O(MAX + n)
Espacio auxiliar: O(MAX)
¿Podemos resolverlo en tiempo O(n) si el rango no está limitado?
Consulte el elemento más pequeño repetido exactamente ‘k’ veces (no limitado a un rango pequeño)
Este artículo es una contribución de Abhijit Shankhdhar . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA