Menu
CoddyTech

练习 #1

Coddy 堆与优先队列:数据结构系列 #7 课程的第 10 课,共 14 课。

challenge icon

挑战

简单

编写一个函数 kSmallest,接收一个整数数组 arr 和一个整数 k,并按升序返回最小的 k 个值。

如果 k 大于数组长度,则按升序返回所有值。如果 k 为零或负数,则返回一个空数组。

你必须使用 MinHeap 类(由 minheap.<ext> 提供),不要使用 sort、slice 等语言内置功能或标准库堆库来计算结果。

亲手试试

#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 = kSmallest(arr, n, k, &rs);
    for (int idx = 0; idx < rs; idx++) { if (idx > 0) printf(" "); printf("%d", r[idx]); }
    printf("\n");
    return 0;
}

堆与优先队列:数据结构系列 #7中的所有课

自己练习: C 在线编译器