LeetCode | 4. Median of Two Sorted Arrays
程序员文章站
2022-05-14 20:19:39
...
4. Median of Two Sorted Arrays
Description
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Solution: (Java)
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int index1 = 0, index2 = 0, medianIndex, count = 0;
medianIndex = (nums1.length + nums2.length) / 2;
int[] arr = new int[medianIndex + 1];
while (index1 < nums1.length && index2 < nums2.length) {
if (nums1[index1] <= nums2[index2]) {
arr[count] = nums1[index1];
index1++;
} else {
arr[count] = nums2[index2];
index2++;
}
count++;
if (count > medianIndex)
break;
}
if (count <= medianIndex) {
if (index1 == nums1.length) {
while (index2 < nums2.length) {
arr[count] = nums2[index2];
index2++;
count++;
if (count > medianIndex)
break;
}
} else {
while (index1 < nums1.length) {
arr[count] = nums1[index1];
index1++;
count++;
if (count > medianIndex)
break;
}
}
}
if ((nums1.length + nums2.length) % 2 == 0)
return (arr[medianIndex-1] + arr[medianIndex])*1.0 / 2;
else
return arr[medianIndex];
}
}
思路
本题的代码还可以再稍微精简一下,不过这样也比较简单易懂吧,先得到中位数的索引位置,然后从两个数组中,依次把较小的数往新的数组填充,一直到中位数的位置,那么新数组的最后一个或者最后两个数的平均值即为中位数。
推荐阅读
-
Leetcode-14 Longest Common Prefix
-
jquery动画4.升级版遮罩效果的图片走廊--带自动运行效果_jquery
-
java中的arrays.sort()代码详解
-
LeetCode:求链表中倒数第k个节点(Python)
-
LeetCode 139. Word Break (断词)
-
Java基础学习总结(129)——Arrays.asList得到的List进行add和remove等操作出现异常解析
-
Java中Arrays.asList()方法详解及实例
-
Java数组高级算法与Arrays类常见操作小结【排序、查找】
-
Java中Arrays类与Math类详解
-
Java中Arrays.asList()方法详解及实例