Conteo de números que aparecen en los rangos dados al menos K veces

Dados N rangos y un número K, la tarea es encontrar el conteo total de números que aparecen al menos K veces en los rangos dados. 

Ejemplos

Entrada: 
N = 3, K = 2 
Rango 1: [91, 94] 
Rango 2: [92, 97] 
Rango 3: [97, 99] 
Salida: 4
Explicación: Los rangos son 91 a 94, 92 a 97, 97 a 99 y los números que ocurrieron al menos 2 veces son 92, 93, 94, 97.

Entrada: 
N = 2, K = 3 
Rango 1 = [1, 4] 
Rango 2 = [5, 9] 
Salida:
Explicación: Ningún elemento apareció 3 veces en los rangos dados. 

Enfoque ingenuo : un enfoque ingenuo sería atravesar cada rango y aumentar el conteo de cada elemento, finalmente verificar si el conteo de cada elemento es suficiente para el valor requerido.
A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ brute-force program to find count of
// numbers appearing in the given
// ranges at-least K times
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the no of occurrence
int countNumbers(int n, int k, int rangeLvalue[],
                              int rangeRvalue[])
{
    int count = 0;
 
    // Map to store frequency of elements
    // in the range
    map<int, int> freq;
 
    for (int i = 0; i < n; i++) {
 
        // increment the value of the elements
        // in all of the ranges
        for (int j = rangeLvalue[i]; j <= rangeRvalue[i]; j++)
        {
            if (freq.find(j) == freq.end())
                freq.insert(make_pair(j, 1));
            else
                freq[j]++;
        }
    }
 
    // Traverse the map to check the frequency
    // of numbers greater than equals to k
    for (auto itr = freq.begin(); itr != freq.end(); itr++)
    {
 
        // check if a number appears atleast k times
        if ((*itr).second >= k) {
 
            // increase the counter
            // if condition satisfies
            count++;
        }
    }
 
    // return the result
    return count;
}
 
// Driver Code
int main()
{
    int n = 3, k = 2;
    int rangeLvalue[] = { 91, 92, 97 };
    int rangeRvalue[] = { 94, 97, 99 };
    cout << countNumbers(n, k, rangeLvalue, rangeRvalue);
    return 0;
}

Java

// Java brute-force program to find count of
// numbers appearing in the given
// ranges at-least K times
import java.io.*;
import java.util.*;
 
class GFG
{
 
    // Function to find the no of occurrence
    static int countNumbers(int n, int k, int[] rangeLvalue,
                                            int[] rangeRvalue)
    {
        int count = 0;
 
        // Map to store frequency of elements
        // in the range
        HashMap<Integer, Integer> freq = new HashMap<>();
 
        // increment the value of the elements
        // in all of the ranges
        for (int i = 0; i < n; i++)
        {
            for (int j = rangeLvalue[i]; j <= rangeRvalue[i]; j++)
            {
                if (!freq.containsKey(j))
                    freq.put(j, 1);
                else
                    freq.put(j, freq.get(j) + 1);
            }
        }
 
        // Traverse the map to check the frequency
        // of numbers greater than equals to k
        for (HashMap.Entry<Integer, Integer> entry : freq.entrySet())
        {
 
            // check if a number appears atleast k times
            if (entry.getValue() >= k)
 
                // increase the counter
                // if condition satisfies
                count++;
        }
 
        // return the result
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 3, k = 2;
        int[] rangeLvalue = {91, 92, 97};
        int[] rangeRvalue = {94, 97, 99};
        System.out.println(countNumbers(n, k, rangeLvalue, rangeRvalue));
    }
}
 
// This code is contributed by
// sanjeev2552

Python3

# Python3 brute-force program to find
# count of numbers appearing in the
# given ranges at-least K times
 
# Function to find the no of occurrence
def countNumbers(n, k, rangeLvalue,    
                       rangeRvalue):
 
    count = 0
 
    # Map to store frequency of elements
    # in the range
    freq = dict()
 
    for i in range(n):
 
        # increment the value of the elements
        # in all of the ranges
        for j in range(rangeLvalue[i],
                       rangeRvalue[i] + 1):
            freq[j] = freq.get(j, 0) + 1
     
    # Traverse the map to check the frequency
    # of numbers greater than equals to k
    for itr in freq:
 
        # check if a number appears
        # atleast k times
        if (freq[itr] >= k):
 
            # increase the counter
            # if condition satisfies
            count += 1
         
    # return the result
    return count
 
# Driver Code
n, k = 3, 2
rangeLvalue = [91, 92, 97]
rangeRvalue = [94, 97, 99]
print(countNumbers(n, k, rangeLvalue,
                         rangeRvalue))
 
# This code is contributed by mohit kumar

C#

// C# brute-force program to find count of
// numbers appearing in the given
// ranges at-least K times
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to find the no of occurrence
    static int countNumbers(int n, int k, int[] rangeLvalue,
                                            int[] rangeRvalue)
    {
        int count = 0;
 
        // Map to store frequency of elements
        // in the range
        Dictionary<int, int> freq = new Dictionary<int, int>();
 
        // increment the value of the elements
        // in all of the ranges
        for (int i = 0; i < n; i++)
        {
            for (int j = rangeLvalue[i]; j <= rangeRvalue[i]; j++)
            {
                if (!freq.ContainsKey(j))
                    freq.Add(j, 1);
                else
                    freq[j] = freq[j] + 1;
            }
        }
 
        // Traverse the map to check the frequency
        // of numbers greater than equals to k
        foreach(KeyValuePair<int, int> entry in freq)
        {
 
            // check if a number appears atleast k times
            if (entry.Value >= k)
 
                // increase the counter
                // if condition satisfies
                count++;
        }
 
        // return the result
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int n = 3, k = 2;
        int[] rangeLvalue = {91, 92, 97};
        int[] rangeRvalue = {94, 97, 99};
        Console.WriteLine(countNumbers(n, k, rangeLvalue, rangeRvalue));
    }
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
 
// JavaScript brute-force program to find count of
// numbers appearing in the given
// ranges at-least K times
     
    // Function to find the no of occurrence
    function countNumbers(n,k,rangeLvalue,rangeRvalue)
    {
        let count = 0;
   
        // Map to store frequency of elements
        // in the range
        let freq = new Map();
   
        // increment the value of the elements
        // in all of the ranges
        for (let i = 0; i < n; i++)
        {
            for (let j = rangeLvalue[i];
            j <= rangeRvalue[i]; j++)
            {
                if (!freq.has(j))
                    freq.set(j, 1);
                else
                    freq.set(j, freq.get(j) + 1);
            }
        }
   
        // Traverse the map to check the frequency
        // of numbers greater than equals to k
        for (let [key, value] of freq.entries())
        {
   
            // check if a number appears atleast k times
            if (value >= k)
   
                // increase the counter
                // if condition satisfies
                count++;
        }
   
        // return the result
        return count;
    }
     
     // Driver Code
    let n = 3, k = 2;
    let rangeLvalue=[91, 92, 97];
    let rangeRvalue =[94, 97, 99];
     
    document.write(countNumbers(n, k, rangeLvalue,
    rangeRvalue));
       
 
 
// This code is contributed by unknown2108
 
</script>
Producción: 

4

 

Solución eficiente : una mejor solución es hacer un seguimiento de los rangos incrementando el valor del elemento más a la izquierda del rango y disminuyendo el siguiente elemento del elemento más a la derecha del rango dado en la array de contadores. Haga esto para todos los rangos. Esto se hace porque da una idea de cuántas veces ocurrió un número en el rango dado al hacer una suma previa.
A continuación se muestra la implementación del enfoque anterior. 

C++

// C++ efficient program to find count of
// numbers appearing in the given
// ranges at-least K times
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the no of occurrence
int countNumbers(int n, int k, int rangeLvalue[],
                              int rangeRvalue[])
{
    int count = 0;
 
    // maximum value of the range
    int maxn = INT_MIN;
    for (int i = 0; i < n; i++)
        if (rangeRvalue[i] > maxn)
            maxn = rangeRvalue[i];
 
    // counter array
    int preSum[maxn + 5] = { 0 };
 
    // incrementing and decrementing the
    // leftmost and next value of rightmost value
    // of each range by 1 respectively
    for (int i = 0; i < n; i++) {
        preSum[rangeLvalue[i]]++;
        preSum[rangeRvalue[i] + 1]--;
    }
 
    // presum gives the no of occurrence of
    // each element
    for (int i = 1; i <= maxn; i++) {
        preSum[i] += preSum[i - 1];
    }
 
    for (int i = 1; i <= maxn; i++) {
 
        // check if the number appears atleast k times
        if (preSum[i] >= k) {
 
            // increase the counter if
            // condition satisfies
            count++;
        }
    }
 
    // return the result
    return count;
}
 
// Driver Code
int main()
{
    int n = 3, k = 2;
 
    int rangeLvalue[] = { 91, 92, 97 };
    int rangeRvalue[] = { 94, 97, 99 };
 
    cout << countNumbers(n, k, rangeLvalue, rangeRvalue);
 
    return 0;
}

Java

// Java efficient program to find count of
// numbers appearing in the given
// ranges at-least K times
class Geeks {
 
// Function to find the no of occurrence
static int countNumbers(int n, int k, int rangeLvalue[],
                                     int rangeRvalue[])
{
    int count = 0;
 
    // maximum value of the range
    int maxn = Integer.MIN_VALUE;
    for (int i = 0; i < n; i++)
        if (rangeRvalue[i] > maxn)
            maxn = rangeRvalue[i];
 
    // counter array
    int preSum[] = new int[maxn + 5];
    for(int i = 0; i < (maxn + 5); i++)
    preSum[i] = 0;
 
    // incrementing and decrementing the
    // leftmost and next value of rightmost value
    // of each range by 1 respectively
    for (int i = 0; i < n; i++)
    {
        preSum[rangeLvalue[i]]++;
        preSum[rangeRvalue[i] + 1]--;
    }
 
    // presum gives the no of occurrence of
    // each element
    for (int i = 1; i <= maxn; i++) {
        preSum[i] += preSum[i - 1];
    }
 
    for (int i = 1; i <= maxn; i++) {
 
        // check if the number appears atleast k times
        if (preSum[i] >= k) {
 
            // increase the counter if
            // condition satisfies
            count++;
        }
    }
 
    // return the result
    return count;
}
 
// Driver Code
public static void main(String args[])
{
    int n = 3, k = 2;
 
    int rangeLvalue[] = { 91, 92, 97 };
    int rangeRvalue[] = { 94, 97, 99 };
 
    System.out.println(countNumbers(n, k, rangeLvalue,
                                        rangeRvalue));
 
}
}
 
// This code is contributed by ankita_saini

Python

# Python efficient program to find count of
# numbers appearing in the given
# ranges at-least K times
 
# Function to find the no of occurrence
def countNumbers(n, k, rangeLvalue, rangeRvalue):
    count = 0
 
    # maximum value of the range
    maxn = -float('inf')
    for i in range(n):
        if rangeRvalue[i] > maxn:
            maxn = rangeRvalue[i]
 
    # counter array
    preSum = [0]*(maxn + 5)
 
    # incrementing and decrementing the
    # leftmost and next value of rightmost value
    # of each range by 1 respectively
    for i in range(n):
        preSum[rangeLvalue[i]] += 1
        preSum[rangeRvalue[i] + 1] -= 1
 
    # presum gives the no of occurrence of
    # each element
    for i in range(1, maxn+1):
        preSum[i] += preSum[i - 1]
 
    for i in range(1, maxn+1):
 
        # check if the number appears atleast k times
        if preSum[i] >= k:
 
            # increase the counter if
            # condition satisfies
            count += 1
 
    # return the result
    return count
 
 
# Driver Code
n = 3
k = 2
 
rangeLvalue = [91, 92, 97]
rangeRvalue = [94, 97, 99]
 
print(countNumbers(n, k, rangeLvalue, rangeRvalue))
 
# This code is contributed by ankush_953

C#

// C# efficient program to
// find count of numbers
// appearing in the given
// ranges at-least K times
using System;
 
class GFG
{
 
// Function to find the
// no of occurrence
static int countNumbers(int n, int k,
                        int []rangeLvalue,
                        int []rangeRvalue)
{
    int count = 0;
 
    // maximum value of the range
    int maxn = Int32.MinValue;
    for (int i = 0; i < n; i++)
        if (rangeRvalue[i] > maxn)
            maxn = rangeRvalue[i];
 
    // counter array
    int []preSum = new int[maxn + 5];
    for(int i = 0; i < (maxn + 5); i++)
    preSum[i] = 0;
 
    // incrementing and decrementing
    // the leftmost and next value
    // of rightmost value of each
    // range by 1 respectively
    for (int i = 0; i < n; i++)
    {
        preSum[rangeLvalue[i]]++;
        preSum[rangeRvalue[i] + 1]--;
    }
 
    // presum gives the no of
    // occurrence of each element
    for (int i = 1; i <= maxn; i++)
    {
        preSum[i] += preSum[i - 1];
    }
 
    for (int i = 1; i <= maxn; i++)
    {
 
        // check if the number
        // appears atleast k times
        if (preSum[i] >= k)
        {
 
            // increase the counter if
            // condition satisfies
            count++;
        }
    }
 
    // return the result
    return count;
}
 
// Driver Code
public static void Main(String []args)
{
    int n = 3, k = 2;
 
    int []rangeLvalue = { 91, 92, 97 };
    int []rangeRvalue = { 94, 97, 99 };
 
    Console.WriteLine(countNumbers(n, k, rangeLvalue,
                                        rangeRvalue));
}
}
 
// This code is contributed
// by ankita_saini

Javascript

<script>
 
// Javascript efficient program to find count of
// numbers appearing in the given
// ranges at-least K times
 
// Function to find the no of occurrence
function countNumbers(n, k, rangeLvalue, rangeRvalue)
{
    var count = 0;
 
    // maximum value of the range
    var maxn = -1000000000;
    for (var i = 0; i < n; i++)
        if (rangeRvalue[i] > maxn)
            maxn = rangeRvalue[i];
 
    // counter array
    var preSum = Array(maxn +5).fill(0);
 
    // incrementing and decrementing the
    // leftmost and next value of rightmost value
    // of each range by 1 respectively
    for (var i = 0; i < n; i++) {
        preSum[rangeLvalue[i]]++;
        preSum[rangeRvalue[i] + 1]--;
    }
 
    // presum gives the no of occurrence of
    // each element
    for (var i = 1; i <= maxn; i++) {
        preSum[i] += preSum[i - 1];
    }
 
    for (var i = 1; i <= maxn; i++) {
 
        // check if the number appears atleast k times
        if (preSum[i] >= k) {
 
            // increase the counter if
            // condition satisfies
            count++;
        }
    }
 
    // return the result
    return count;
}
 
// Driver Code
var n = 3, k = 2;
var rangeLvalue = [91, 92, 97];
var rangeRvalue = [94, 97, 99];
document.write( countNumbers(n, k, rangeLvalue, rangeRvalue));
 
 
</script>
Producción: 

4

 

Complejidad de tiempo : O(N + max(rangeRvalue[])) 
Espacio auxiliar : O(N)
 

Publicación traducida automáticamente

Artículo escrito por Subash23 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *