C ++中两个排序数组的第K个元素
在本教程中,我们将编写一个程序,该程序从两个排序数组的合并数组中找到第k个元素。
让我们看看解决问题的步骤。
初始化两个排序的数组。
初始化一个大小为m+n的空数组。
将两个数组合并到新数组中。
从合并数组返回k-1元素。
示例
让我们看一下代码。
#includeusing 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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短