이 튜토리얼에서는 두 개의 정렬된 배열의 병합된 배열에서 k번째 요소를 찾는 프로그램을 작성할 것입니다.
문제를 해결하는 단계를 살펴보겠습니다.
- 2개의 정렬된 배열을 초기화합니다.
- m + n 크기의 빈 배열을 초기화합니다.
- 두 배열을 새 배열로 병합합니다.
- 병합된 배열에서 k - 1 요소를 반환합니다.
예시
코드를 봅시다.
#include <iostream>
using namespace std;
int findKthElement(int arr_one[], int arr_two[], int m, int n, int k) {
int sorted_arr[m + n];
int i = 0, j = 0, index = 0;
while (i < m && j < n) {
if (arr_one[i] < arr_two[j]) {
sorted_arr[index++] = arr_one[i++];
}else {
sorted_arr[index++] = arr_two[j++];
}
}
while (i < m) {
sorted_arr[index++] = arr_one[i++];
}
while (j < n) {
sorted_arr[index++] = arr_two[j++];
}
return sorted_arr[k - 1];
}
int main() {
int arr_one[5] = {1, 3, 5, 7, 9}, arr_two[5] = {2, 4, 6, 8, 10};
int k = 7;
cout << findKthElement(arr_one, arr_two, 5, 4, k) << endl;
return 0;
} 출력
위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
7
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.