leetcode_【4】寻找两个有序数组的中位数

1.题目描述

给定两个大小为 m 和 n 的有序数组 nums1nums2

请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1nums2 不会同时为空。

示例 1:

nums1 = [1, 3]
nums2 = [2]

则中位数是 2.0

示例 2:

nums1 = [1, 2]
nums2 = [3, 4]

则中位数是 (2 + 3)/2 = 2.5

2.解题思路

排序输出中间值,但是复杂度不符合题意

3.代码

方法1:复杂度不符合

1
2
3
4
5
6
7
8
9
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
//将两个数组放到一个数组中并从小到大排序
int[] ints = ArrayUtils.addAll(nums1, nums2);
Arrays.sort(ints);
//奇数个数返回 中间索引,偶数个返回最中间的两个数的平均,注意/2可能为小数,要/2d或者/2.0强转为double类型
if(ints.length%2==0){
return (ints[(ints.length+1)/2]+ints[(ints.length+1)/2-1])/2d;
}else return ints[(ints.length-1)/2];
}

方法2:复杂度还是不符合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n1Length = nums1.length;
int n2Length = nums2.length;
int totalLength = n1Length + n2Length;
int arrayIndex = 0;
int maxArrayIndex = totalLength / 2;
int n1Index = 0;
int n2Index = 0;

int last1 = 0;
int last2 = 0; //用于记录偶数情况下的last1的前一个数
while (arrayIndex <= maxArrayIndex) {
last2 = last1;
//只剩下nums2的情况了,nums1的全部数跟nums2排序都还没到达中间
if (n1Index >= n1Length) {
last1 = nums2[n2Index++];
//只剩下nums1的情况了,nums2的全部数跟nums1排序都还没到达中间
} else if (n2Index >= n2Length) {
last1 = nums1[n1Index++];
} else {
//哪个小哪个索引坐标【n1Index或者n2Index】开始滑动
if (nums1[n1Index] <= nums2[n2Index]) {
last1 = nums1[n1Index++];
} else {
last1 = nums2[n2Index++];
}
}
//整体数组【nums1 U nums2】的索引每循环依次自增1,直到到达整体数组中间位置
arrayIndex++;
}
if (totalLength % 2 == 0) {
return (last1 + last2) / 2.0;
} else {
return last1;
}
}
}

4.提交记录

leetcode提交结果

文章目录
  1. 1. 1.题目描述
  2. 2. 2.解题思路
  3. 3. 3.代码
  4. 4. 4.提交记录
| 139.6k