/* 主要思路:要找到第 k (k>1) 小的元素,那么就取 pivot1 = nums1[k/2-1] 和 pivot2 = nums2[k/2-1] 进行比较
* 这里的 "/" 表示整除
* nums1 中小于等于 pivot1 的元素有 nums1[0 .. k/2-2] 共计 k/2-1 个
* nums2 中小于等于 pivot2 的元素有 nums2[0 .. k/2-2] 共计 k/2-1 个
* 取 pivot = min(pivot1, pivot2),两个数组中小于等于 pivot 的元素共计不会超过 (k/2-1) + (k/2-1) <= k-2 个
* 这样 pivot 本身最大也只能是第 k-1 小的元素
* 如果 pivot = pivot1,那么 nums1[0 .. k/2-1] 都不可能是第 k 小的元素。把这些元素全部 "删除",剩下的作为新的 nums1 数组
* 如果 pivot = pivot2,那么 nums2[0 .. k/2-1] 都不可能是第 k 小的元素。把这些元素全部 "删除",剩下的作为新的 nums2 数组
* 由于我们 "删除" 了一些元素(这些元素都比第 k 小的元素要小),因此需要修改 k 的值,减去删除的数的个数
*/
#include <vector>
#include <stdio.h>
using namespace std;
int getKthElement(const std::vector<int>& arr1, const std::vector<int>& arr2, int k) {
int n1 = arr1.size();
int n2 = arr2.size();
int index1 = 0, index2 = 0;
while (true) {
if (index1 == n1) {
return arr2[index2 + k - 1];
}
if (index2 == n2) {
return arr1[index1 + k - 1];
}
if (k == 1) {
return min(arr1[index1], arr2[index2]);
}
int newIndex1 = min(index1 + k / 2 - 1, n1 - 1);
int newIndex2 = min(index2 + k / 2 - 1, n2 - 1);
int pivot1 = arr1[newIndex1];
int pivot2 = arr2[newIndex2];
if (pivot1 <= pivot2) {
k -= newIndex1 - index1 + 1;
index1 = newIndex1 + 1;
} else {
k -= newIndex2 - index2 + 1;
index2 = newIndex2 + 1;
}
}
}
double findMedianSortedArrays(std::vector<int>& arr1, std::vector<int>& arr2) {
int totalLength = arr1.size() + arr2.size();
if (totalLength % 2 == 1) {
return getKthElement(arr1, arr2, (totalLength + 1) / 2);
} else {
return (getKthElement(arr1, arr2, totalLength / 2) + getKthElement(arr1, arr2, totalLength / 2 + 1)) / 2.0;
}
}
int main(){
std::vector<int> arr1 = {1, 3, 4, 9};
std::vector<int> arr2 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int res = findMedianSortedArrays(arr1, arr2);
printf("%d\n", res);
return 1;
}
两有序数组的中位数
于 2023-04-21 18:23:45 首次发布