1. 题目
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
https://leetcode.com/problems…
2. 思路
从两个有序数组中查找中位值。转换为查找K-th分位值。分别从两个数组中查找K/2分位进行比较,小的那个数组的K/2个一定是在前K里面的,因此小的可以向前跳跃K/2。然后递归求解下K/2-th分位的值。
找到中位值的情况,就是奇数位时找中间的一个返回。偶数位时找到中间两个返回其均值。
3. 代码
耗时:108ms
#include <vector>
using std::vector;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int k = (len1 + len2) / 2;
if ((len1 + len2) % 2 == 1) {
return findKSortedArrays(nums1, 0, nums2, 0, k + 1);
} else {
return (findKSortedArrays(nums1, 0, nums2, 0, k) + findKSortedArrays(nums1, 0, nums2, 0, k + 1) ) / 2;
}
}
double findKSortedArrays(vector<int>& nums1, int s1, vector<int>& nums2, int s2, int k) {
if (s1 == nums1.size()) {
return nums2[s2+k-1];
}
if (s2 == nums2.size()) {
return nums1[s1+k-1];
}
if (k == 1) {
return nums1[s1] < nums2[s2] ? nums1[s1] : nums2[s2];
}
int half_k = k / 2;
int kp1 = half_k;
int kp2 = half_k;
if (s1 + half_k >= nums1.size()) {
kp1 = nums1.size() - s1;
}
if (s2 + half_k >= nums2.size()) {
kp2 = nums2.size() - s2;
}
int v1 = nums1[s1 + kp1 - 1];
int v2 = nums2[s2 + kp2 - 1];
if (v1 == v2) {
if (kp1 + kp2 == k) {
return v1;
} else {
return findKSortedArrays(nums1, s1 + kp1, nums2, s2 + kp2, k - kp1 -kp2);
}
} else if (v1 < v2) {
return findKSortedArrays(nums1, s1 + kp1, nums2, s2, k - kp1);
} else {
return findKSortedArrays(nums1, s1, nums2, s2 + kp2, k - kp2);
}
}
};