Practice #1
Coddy의 힙 & 우선순위 큐 - 자료구조 시리즈 #7 코스 레슨 — 14개 중 10번째.
챌린지
쉬움정수 배열 arr와 정수 k를 입력받아, 가장 작은 k개의 값을 오름차순으로 정렬하여 반환하는 함수 kSmallest를 작성하세요.
만약 k가 배열의 크기보다 크다면, 모든 값을 정렬하여 반환하세요. k가 0이거나 음수라면, 빈 배열을 반환하세요.
반드시 MinHeap 클래스를 사용해야 합니다 (minheap.<ext>에 제공됨). 결과를 계산하기 위해 sort, slice 또는 표준 라이브러리의 힙(heap) 라이브러리와 같은 언어 내장 기능을 사용하지 마세요.
직접 해보기
#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;
}