Leetcode Problem4 Median of Two Sorted Arrays

本文介绍两种方法求解两个有序数组的中位数。思路一采用递归法,通过比较两个数组的中位数缩小查找范围,最终找到中位数,时间复杂度为O(log(max(m,n)))。思路二是直接合并排序两个数组后找中位数,时间复杂度为O(log(m+n))。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)).

思路1:本题毫无疑问第一反应肯定是使用递归求解。此题是求两个有序序列的中位数,如果第一个序列的中位数小于第二个序列的中位数,则中位数一定在第一个序列的后半部分,或者第二个序列的前半部分。反之则在第一个序列的前半部分和第二个序列的后半部分。如此递归下去就可以了。

可知只算法的时间复杂度是o(log(max(m,n)))符合题目的要求。代码如下(已通过leetcode);

思路2:可以直接将这个两个有序的序列直接排序,时间复杂度是o(log(n+m))

/*

**思路1的代码

*/

public class Solution {  
 
   private double findKthSortedArrays(int A[], int astart, int aend,  
                                      int B[], int bstart, int bend, int k) {  
       int m = aend - astart, n = bend - bstart;  
       if (m < n) {  
           return findKthSortedArrays(B, bstart, bend, A, astart, aend, k);  
       }  
       if (n == 0)  
           return A[astart + k - 1];  
       if (k == 1)  
           return Math.min(A[astart], B[bstart]);  
 
       int pb = Math.min(k / 2, n), pa = k - pb;  
       if (A[astart + pa - 1] > B[bstart + pb - 1])  
           return findKthSortedArrays(A, astart, aend, B, bstart + pb, bend, k - pb);  
       else if (A[astart + pa - 1] < B[bstart + pb - 1])  
           return findKthSortedArrays(A, astart + pa, aend, B, bstart, bend, k - pa);  
       else  
           return A[astart + pa - 1];  
   }  
 
   public double findMedianSortedArrays(int nums1[], int nums2[]) {  
       int m = nums1.length, n = nums2.length;  
       if ((n + m) % 2 == 1)  
           return findKthSortedArrays(A, 0, m, B, 0, n, (n + m) / 2 + 1);  
       else  
           return (findKthSortedArrays(A, 0, m, B, 0, n, (n + m) / 2 + 1) +  
                   findKthSortedArrays(A, 0, m, B, 0, n, (n + m) / 2)) / 2.0;  
   }  
}  

今天就更新到这,明天有时间的话继续更新,继续刷leetcode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值