LeetCode 04:寻找两个有序数组的中位数(Java实现)
- 题目
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。你可以假设 nums1 和 nums2 不会同时为空。示例 1:nums1 = [1, 3],nums2 = [2],则中位数是 2.0示例 2:nums1 = [1, 2],nums2 = [3, 4],则中位数是 (2 + 3)/2 = 2.5来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 - 思路1:将两个数组连接,排序,找中位数
- 代码如下
public double findMediaSortedArrays(int[] nums1,int[] nums2){
int l1 = nums1.length;
int l2 = nums2.length;
int[] nums = new int[l1+l2];
if(l1==0){
if(l2%2==0){
return (nums2[l2/2-1]+nums2[l2/2])/2.0;
}
else return (nums2[l2/2]);
}
if(l2==0){
if(l1%2==0){
return (nums1[l1/2-1]+nums1[l1/2])/2.0;
}
else return (nums1[l1/2]);
}
int count = 0;
int i = 0,j = 0;
while(count<=l1+l2){
if(nums1[i]<nums2[j]){
nums[count++] = nums1[i++];
}
else nums[count++] = nums2[j++];
if(i==l1){
while(j!=l2){
nums[count++] = nums2[j++];
}
break;
}
if(j==l2){
while(i!=l1){
nums[count++] = nums1[i++];
}
break;
}
}
if(count%2==0){
return (nums[count/2-1]+nums[count/2])/2.0;
}
else return (nums[count/2]);
}
}
}
- 注意事项、细节
1、当两个数组内元素数量之和(count)为偶数时,应该"/2.0"而不是"/2"。
2、涉及了数组就要防止“溢出”,这题中涉及了多处容易“溢出”的地方,应格外小心。 - 结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/93e4f88dc2183d8f7553fb430f919fd4.png)