leetcode-Median of Two Sorted Arrays
题目:
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.
主要意思是:有两个有序的数组,要找到这两个数组中的中位数。
思路:
这里有三个点需要着重注意:
- 两个数组都是有序的
- 两个数组中,可能其中一个是空值(考虑边界问题)
在遍历数组的过程中,要将下标的检查放在最前面,防止一开始就出现有数组为空而越界的情况 - 要求算法的平均复杂度是log(m+n)
数组的有序,为平均复杂度提供了可能,因此要充分理由有序的优势。为了降低复杂度,可以使用加大空间复杂度的方式。这道题目的主要思路是借助了如何将两个有序数组并称一个有序数组的思路。
代码:
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int s1_length=nums1.length;
int s2_length=nums2.length;
int low=0;
int high=s1_length+s2_length-1;
int s1_low=0;
int s1_high=s1_length-1;
int s2_low=0;
int s2_high=s2_length-1;
int[] num_res=new int[s1_length+s2_length];
while(low<=high){
//考虑某个数组越界了之后的情况
if(s1_low>s1_high||s2_low>s2_high){
break;
}
//找到放入low中的值
if(nums1[s1_low]<nums2[s2_low]){
num_res[low++]=nums1[s1_low];
s1_low++;
}
else{
num_res[low++]=nums2[s2_low];
s2_low++;
}
//找到放入high中的值
if(nums1[s1_high]>nums2[s2_high]){
num_res[high--]=nums1[s1_high];
s1_high--;
}
else{
num_res[high--]=nums2[s2_high];
s2_high--;
}
}
//处理如果两个数组中的一个数组提前被访问完
while(s1_low<=s1_high){
num_res[low++]=nums1[s1_low++];
}
while(s2_low<=s2_high){
num_res[low++]=nums2[s2_low++];
}
if((s1_length+s2_length)%2==0){
int mid=(s1_length+s2_length)/2;
return ((num_res[mid]+num_res[mid-1])/2.0);
}
else{
int mid=(s1_length+s2_length)/2;
return (num_res[mid]);
}
}