题目描述:
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int h1=0;
int h2=0;
int m = nums1.length;
int n = nums2.length;
int length = m+n;
int[] nums3 = new int[length];
int count=0;
while(count!=length){
//首先判断指针是否到达边界,否则容易发生越界
if(h1==m){
while(h2!=n){
nums3[count++]=nums2[h2++];
}
break;
}
if(h2==n){
while(h1!=m){
nums3[count++]=nums1[h1++];
}
break;
}
//判断数的大小,把nums1和nums2更新到新建数组中
if(nums1[h1]<nums2[h2]){
nums3[count++]=nums1[h1++];
}
else{
nums3[count++]=nums2[h2++];
}
}
if(length%2==1){
return nums3[(length-1)/2];
}
else{
//除以2.0可以精确到小数点后两位,这个一直没想起来
return (nums3[length/2]+nums3[length/2-1])/2.0;
}
}
}
使用了两个指针指向两个数组,由于数组已排序,移动指针判断大小将两个数组的元素赋值到新建nums3数组中。
应注意判断指针是否到达两个数组边界,否则会报错(数组越界)。
执行用时 :
2 ms
, 在所有 Java 提交中击败了
100.00%
的用户
内存消耗 :
40.4 MB
, 在所有 Java 提交中击败了
100.00%
的用户
这个方法应该有很多人想到,不过没想到我的代码消耗的资源竟然这么少(哈哈,沾沾自喜一下)。