博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeedCode刷题感悟
阅读量:3959 次
发布时间:2019-05-24

本文共 920 字,大约阅读时间需要 3 分钟。

LeedCode刷题感悟

寻找两个有序数组的中位数:

在这里插入图片描述
其实这就是一个二路归并排序问题!代码如下在这里插入代码片

class Solution {

public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
double result = 0;//定义结果
int length1 = nums1.length;//nums1的长度
int length2 = nums2.length;//nums2的长度
int a = 0, b = 0;//最开始a,b分别指向两数组的开头,后面一位比较nums1[a]与nums2[b]
int k = 0;
int[] num = new int[10000];//存储新的数组
while (a < length1 && b < length2) {
while (nums1[a] <= nums2[b]) {
num[k++] = nums1[a++];
if (a >= length1)
break;//注意这个break与下一个break的区别;这个跳出本次循环,下一个跳出整个
}
if (a >= length1)
break;
while (nums1[a] > nums2[b]) {
num[k++] = nums2[b++];
if (b >= length2)
break;
}
}
while (a < length1)
num[k++] = nums1[a++];
while (b < length2)
num[k++] = nums2[b++];
//将剩余的部分存入num中
if ((length1 + length2) % 2 == 0)
result = (num[(length1 + length2) / 2] + num[(length1 + length2) / 2 - 1]) / 2.0;
else
result = (double) (num[(length1 + length2) / 2]);
return result;
}
}

又是一次笔记,再接再厉!

转载地址:http://silzi.baihongyu.com/

你可能感兴趣的文章