LeetCode之寻找两个有序数组的中位数(超时、可过75%)
题目
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
思路
我的思路就是将两个有序的数组进行归并,分为两个数组的和是奇数还是偶数找到对应的mid值得出中位数。
代码
1.public findMedianSortedArrays(int[] nums1, int[] nums2) 是主函数,分为一个数组为空与两个都不为空的情况返回中位数。
2. public double findRes(int[] nums)这个是直接返回另一个数组的中位数。
3. public double merge(int[] nums1,int[] nums2,int mid)这个是合并两个数组(这里没有全部合并只合并到mid值),并且返回中位数。
注:
target = nums[n/2]+nums[(n/2)-1];
target = target / 2;
这两句分开的原因是如果合在一起为 :
target = (nums[n/2]+nums[(n/2)-1]/2;
结果是它先进行int类型的运算,结果也是int的结果,当隐式转换为double时它也是int转换而来的所以不对。
class Solution {
int[] num = new int[500000];
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n = nums1.length + nums2.length;
double res;
int mid;
if(nums1.length == 0){
res = findRes(nums2);
return res;
}
if(nums2.length == 0){
res = findRes(nums1);
return res;
}
mid= n/2;
res = merge(nums1,nums2,mid);
return res;
}
public double findRes(int[] nums){
int n = nums.length;
double target;
if(n == 1){
return nums[0];
}
if(n % 2 != 0){
target = nums[n/2];
}else{
target = nums[n/2]+nums[(n/2)-1];
target = target / 2;
}
return target;
}
public double merge(int[] nums1,int[] nums2,int mid){
int i = 0,j = 0;
double target;
int n = nums1.length + nums2.length;
for(int k = 0;k <=mid;k++){
if(i >= nums1.length){
num[k] = nums2[j++];
continue;
}
if(j >= nums2.length){
num[k] = nums1[i++];
continue;
}
if(nums1[i] <= nums2[j]){
num[k] = nums1[i++];
}else{
num[k] = nums2[j++];
}
}
if(n % 2 != 0){
target = num[mid];
}else{
target = num[mid]+num[mid-1];
target = target / 2;
}
return target;
}
}
虽然只过了一部分测试用例,但是也可以参考一下自己的代码。