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)).
这个题目实际上就是先用快速排序进行合并,然后求中间值。
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int [] num = new int [nums1.length+nums2.length];
int index1=0;
int index2=0;
int index = 0;
while(index1<nums1.length&&index2<nums2.length){
if(nums1[index1]<nums2[index2]){
num[index]=nums1[index1];
index1++;
}
else{
num[index]=nums2[index2];
index2++;
}
index++;
}
while(index1<nums1.length){
num[index++]=nums1[index1++];
}
while(index2<nums2.length){
num[index++]=nums2[index2++];
}
if(index%2!=0){
index = num.length/2;
return num[index];
}
else{
index = num.length/2;
return (num[index]+num[index-1])/(double)2;
}
}
}
本文介绍了一种求两个已排序数组中位数的方法。通过合并两个数组并使用快速排序,确保整体运行时间复杂度为O(log(m+n))。代码示例展示了如何实现这一过程。
6万+

被折叠的 条评论
为什么被折叠?



