c++合并动态数组vector,求中位数

该博客探讨如何使用C++将两个已排序的动态数组(vector)合并,并在O(log(m+n))的时间复杂度内计算合并后的中位数。通过示例解释了当数组大小分别为[1,3]和[2],以及[1,2]和[3,4]时的计算过程,中位数分别为2和2.5。文章遵循的约束条件包括数组长度不超过1000,且所有元素在-10^6到10^6之间。" 111557248,10324379,如何更改vsftp匿名用户的默认登录目录,"['服务器管理', 'FTP服务', 'Linux系统', '配置文件']
摘要由CSDN通过智能技术生成

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

The overall run time complexity should be O(log (m+n)).

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

Constraints:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106

class Solution {
   
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>&
当处理超大数组时,我们可以采用基排序的外部排序算法。外部排序将据分成多个块,每次只处理一部分据,并在最后将这些块合并起来得到最终的排序结果。下面是一个使用基排序对超大数组进行从小到大和从大到小排序的示例代码: ```cpp #include <iostream> #include <fstream> #include <vector> #include <algorithm> const int MAX_DIGITS = 10; // 字的最大位 // 获取字的某个位上的值 int getDigit(int num, int digit) { for (int i = 0; i < digit - 1; i++) { num /= 10; } return num % 10; } // 基排序 void radixSort(std::vector<int>& data, bool ascending) { int maxNum = *std::max_element(data.begin(), data.end()); // 获取最大值 int digitNum = 1; // 位 while (maxNum > 10) { maxNum /= 10; digitNum++; } std::vector<std::vector<int>> buckets(10); // 桶数组 std::vector<int> temp(data.size(), 0); // 临时数组 for (int d = 1; d <= digitNum; d++) { // 将据分配到桶中 for (int i = 0; i < data.size(); i++) { int digit = getDigit(data[i], d); buckets[digit].push_back(data[i]); } // 将桶中的据按顺序放回数组 int index = 0; if (ascending) { for (int i = 0; i < 10; i++) { for (int j = 0; j < buckets[i].size(); j++) { data[index++] = buckets[i][j]; } buckets[i].clear(); } } else { for (int i = 9; i >= 0; i--) { for (int j = 0; j < buckets[i].size(); j++) { data[index++] = buckets[i][j]; } buckets[i].clear(); } } } } int main() { std::ifstream inFile("data.txt"); // 打开输入文件 std::vector<int> data; int num; while (inFile >> num) { // 从文件中读取据 data.push_back(num); } inFile.close(); // 关闭输入文件 radixSort(data, true); // 从小到大排序 std::ofstream outFile("sorted_data.txt"); // 打开输出文件 for (int i = 0; i < data.size(); i++) { // 将排序结果写入文件 outFile << data[i] << " "; } outFile.close(); // 关闭输出文件 return 0; } ``` 在上述示例代码中,我们使用了桶数组来存储每个字在当前位上的值。然后,根据需要的排序顺序,按顺序或逆序将桶中的据放回原数组。通过多次迭代,逐位进行排序,最终得到排序结果。 请注意,代码中的 `data.txt` 是输入文件,其中包含待排序的据。排序结果将写入 `sorted_data.txt` 文件中。 希望这可以帮助到您!如有任何疑问,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

群野

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值