练习 #3
Coddy 堆与优先队列:数据结构系列 #7 课程的第 12 课,共 14 课。
挑战
简单编写一个函数 kthSmallest,接收一个整数数组 arr 和一个正整数 k,并返回第 k 小的值(从 1 开始计数)。因此,k = 1 时返回最小值,k = 2 时返回第二小的值,以此类推。
如果 k 超出范围(小于 1 或大于数组长度),则返回 -1。
你必须使用 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 r = kthSmallest(arr, n, k);
printf("%d\n", r);
return 0;
}
堆与优先队列:数据结构系列 #7中的所有课
自己练习: C 在线编译器