Menu
Coddy logo textTech

Practice #2

Lección 11 de 14 del curso Heaps y Colas de Prioridad - Serie de Estructuras de Datos #7 de Coddy.

challenge icon

Desafío

Fácil

Escribe una función kLargest que reciba un arreglo de enteros arr y un entero k, y devuelva los k valores más grandes en orden ascendente.

Si k es mayor que el arreglo, devuelve todos los valores ordenados. Si k es cero o negativo, devuelve un arreglo vacío.

Debes utilizar la clase MinHeap (proporcionada en minheap.<ext>) — no utilices funciones integradas del lenguaje como sort, slice o librerías de heap de la biblioteca estándar para calcular el resultado.

Pruébalo tú mismo

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "solution.h"

int main() {
    char line[8192];
    char tline[64];
    if (!fgets(line, sizeof(line), stdin)) line[0] = '\0';
    if (!fgets(tline, sizeof(tline), stdin)) tline[0] = '\0';
    int arr[4096];
    int n = 0;
    char* tok = strtok(line, " \t\r\n");
    while (tok) { arr[n++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
    int k = atoi(tline);
    int rs = 0;
    int* r = kLargest(arr, n, k, &rs);
    for (int idx = 0; idx < rs; idx++) { if (idx > 0) printf(" "); printf("%d", r[idx]); }
    printf("\n");
    return 0;
}

Todas las lecciones de Heaps y Colas de Prioridad - Serie de Estructuras de Datos #7