LeetCode Top100【困难】
作者:互联网
目录
目录困难
4. 寻找两个正序数组的中位数
- 分成两步来做理解更加简单。先消费完一个数组,再消费另外一个数组
rst1
,rst2
的获取比较巧妙
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
//归并排序部分算法,主要是看是奇偶
int l1 = nums1.length;
int l2 = nums2.length;
int c1 = 0;
int c2 = 0;
int left = (l1 + l2 - 1) / 2;
int right = (l1 + l2) / 2;
int rst1 = 0;
int rst2 = 0;
boolean finish = false;
//只要有一个达到末尾就退出
while (c1 < l1 && c2 < l2) {
if (nums1[c1] <= nums2[c2]) {
rst2 = nums1[c1];
if (c1 + c2 == right) {
finish = true;
break;
}
rst1 = nums1[c1];
c1++;
} else {
rst2 = nums2[c2];
if (c1 + c2 == right) {
finish = true;
break;
}
rst1 = nums2[c2];
c2++;
}
}
if (!finish) {
if (c1 < l1) {
while (c1 < l1) {
rst2 = nums1[c1];
if (c1 + c2 == right) {
break;
}
rst1 = nums1[c1];
c1++;
}
} else {
while (c2 < l2) {
rst2 = nums2[c2];
if (c1 + c2 == right) {
break;
}
rst1 = nums2[c2];
c2++;
}
}
}
if (left == right) {
return rst2;
} else {
return (rst1 + rst2) / 2;
}
}
}
标签:int,困难,nums1,l2,数组,l1,c1,Top100,LeetCode 来源: https://www.cnblogs.com/wftop1/p/16394341.html