leetcode Median of Two Sorted Arrays
程序员文章站
2022-05-14 20:19:33
...
题目:
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)).
You may assume nums1 and nums2 cannot be both empty.
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
思路:
找中位数可以等价于找第k小的数,k=(m+n)/2。
先不考虑时间复杂度,比较容易想到的就是将两个nums合起来排序,然后输出第k个数,k=(m+n)/2。由于两个nums已经是分别有序,所以用两个指针分别去遍历这两个数组并比较大小将较小的依次放入另外一个数组里,时间复杂度是o(m+n)。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
size_t n1 = nums1.size(), n2 = nums2.size();
size_t n = n1+n2;
vector<int> nums(n,0);
assert(n > 0);
nums1.push_back(INT_MAX);
nums2.push_back(INT_MAX);
size_t i = 0, j = 0, k = 0;
while(i < n1 || j < n2) {
if (nums1[i] <= nums2[j]) {
nums[k++] = nums1[i++];
}
else
nums[k++] = nums2[j++];
}
return ((n%2) ? (double)nums[(n-1)/2]:(double)(nums[(n-1)/2]+nums[n/2])/2);
}
};
要求的时间复杂度是o(log(m+n)),很容易想到用二分法。哪具体怎么做呢?突破点在两个数组分别有序。若数组1的第k/2个数小于数组2的第k/2个数,推出数组1的第k/2个数至多为(k/2 + k/2 -1)大,不可能是第k小的数。也就是说第k小的数不可能出现在数组1的前k/2里,因此可以把数组1的前k/2个数去掉。同理,若数组1的第k/2个数大于数组2的第k/2个数,去掉数组2的前k/2个数。若数组1的第k/2个数等于数组2的第k/2个数,则找到了第k小的数。
当然k/2不一定为整数,需要处理一下。
class Solution {
int findkthsmallest(vector<int>::iterator a, int m , vector<int>::iterator b, int n, int k)
{
if(m > n)
return findkthsmallest(b, n, a, m, k);
if(m == 0)
return *(b+k-1);
if(k == 1)
return min(*a, *b);
int pa = min(k/2, m) ;
int pb = k - pa;
if(*(a+pa-1) < *(b+pb-1))
return findkthsmallest(a+pa, m - pa, b, n , k-pa);
else if(*(a+pa-1) > *(b+pb-1))
return findkthsmallest(a, m, b+pb, n-pb, k-pb);
else
return *(a+pa-1);
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int>:: iterator a = nums1.begin();
vector<int>:: iterator b = nums2.begin();
int m = nums1.size();
int n = nums2.size();
int total = m + n ;
if(total%2 == 1)
return (double) findkthsmallest(a, m, b, n, total/2 + 1);
else
return (double)(findkthsmallest(a, m, b, n, total/2) + findkthsmallest(a, m, b, n, total/2 +1))/2 ;
}
};
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
LeetCode 21. 合并两个有序链表 Merge Two Sorted Lists
-
[LeetCode]Merge Two Sorted Lists(Python)
-
【LeetCode】4. Median of Two Sorted Arrays
-
1.Merge Two Sorted Arrays. py/合并排序有序数列
-
LeetCode 4. 两个排序数组的中位数 Median of Two Sorted Arrays
-
算法练习(3):Median of Two Sorted Arrays
-
LeetCode算法系列:4、Median of Two Sorted Arrays
-
4. Median of Two Sorted Arrays
-
4. Median of Two Sorted Arrays