LeetCode - 寻找两个正序数组的中位数
官方链接
给定两个大小分别为m和n的正序(从小到大)数组nums1和nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为O(log (m+n))。
示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
提示:
- nums1.length == m
- nums2.length == n
- 0 <= m <= 1000
- 0 <= n <= 1000
- 1 <= m + n <= 2000
- -106 <= nums1[i], nums2[i] <= 106
我的答案
class Solution {public double findMedianSortedArrays(int[] nums1, int[] nums2) {int totalLength = nums1.length + nums2.length;int[] nums = new int[totalLength];int i = 0, j = 0;while (i + j < totalLength / 2 + 2) {if (i < nums1.length && j < nums2.length) {if (nums1[i] < nums2[j]) {nums[i + j] = nums1[i];i++;} else {nums[i + j] = nums2[j];j++;}continue;}if (i < nums1.length) {nums[i + j] = nums1[i];i++;continue;}if (j < nums2.length) {nums[i + j] = nums2[j];j++;continue;}break;}if ((totalLength & 1) == 0) {return (double) (nums[totalLength / 2 - 1] + nums[totalLength / 2]) / 2;}return nums[totalLength / 2];}
}
我的题解
应该还可以再简单点,声明的总数组长度只需要两位就行了,中位数只看最中间两位。
好像不要新数组也行,后面再研究下
思路
两个数组已经排好序,分别便利取出两个数组的数相互对比,谁大,谁放到新数组里,然后遍历下一个
有点类似于,归并排序的思想:将两个排序好的子序列合并成一个最终的排序序列
解题过程
1)新建一个大数组,用来存储遍历的值
2)遍历两个数组,对比取出来的数,谁小谁先放,然后谁的索引 + 1
3)大概遍历一半多一个,就停止,因为中位数就是取中间那个数(如果是偶数,就是中间两个数的平均数)
4)最后根据所有数的个数是整数还是奇数进行取值
复杂度
- 时间复杂度:𝑂(𝑁)
- 空间复杂度:𝑂(𝑁)
