思路:暴力
// @Title: 寻找两个正序数组的中位数 (Median of Two Sorted Arrays)
// @Author: qisiii
// @Date: 2021-12-16 12:49:46
// @Runtime: 2 ms
// @Memory: 39.8 MB
// @comment: 暴力
// @flag: RED
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] result=new int[nums1.length+nums2.length];
int n1=0,n2=0,i=0;
while(n1<nums1.length&&n2<nums2.length){
if (nums1[n1] < nums2[n2]) {
result[i]=nums1[n1];
n1++;
}else {
result[i]=nums2[n2];
n2++;
}
i++;
}
boolean isN1=n1==nums1.length;
if (isN1){
for (; n2 < nums2.length; n2++) {
result[i]=nums2[n2];
i++;
}
}else {
for (; n1 < nums1.length; n1++) {
result[i]=nums1[n1];
i++;
}
}
if (result.length%2==0){
return (double) (result[result.length/2-1]+result[result.length/2])/2;
}else {
return result[result.length/2];
}
}
}
+++ title = “寻找两个正序数组的中位数 (Median of Two Sorted Arrays)” draft = false +++
思路:节省空间
// @Title: 寻找两个正序数组的中位数 (Median of Two Sorted Arrays)
// @Author: qisiii
// @Date: 2021-12-16 14:00:37
// @Runtime: 1 ms
// @Memory: 39.7 MB
// @comment: 节省空间
// @flag: BLUE
class Solution {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int result = nums1.length + nums2.length;
int left = 0, right = 0;
int n1 = 0, n2 = 0, i = 0;
while (n1 + n2 < result / 2 + 1) {
right = left;
if (nums1.length == 0) {
left = nums2[n2++];
} else if (nums2.length == 0) {
left = nums1[n1++];
} else if (n1 < nums1.length && n2 < nums2.length) {
if (nums1[n1] < nums2[n2]) {
left = nums1[n1++];
} else {
left = nums2[n2++];
}
} else {
Boolean isN1Min = n1 == nums1.length;
if (!isN1Min) {
left = nums1[n1++];
} else {
left = nums2[n2++];
}
}
}
if (result % 2 == 0) {
return (double) (left + right) / 2;
} else {
return left;
}
}
}