LeetCode Median of Two Sorted Arrays

本文介绍了一种求两个已排序数组中位数的方法。通过合并两个数组并使用快速排序,确保整体运行时间复杂度为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)).

这个题目实际上就是先用快速排序进行合并,然后求中间值。

public class Solution {
    	public double findMedianSortedArrays(int[] nums1, int[] nums2) {
       int [] num = new int [nums1.length+nums2.length];
       int index1=0;
       int index2=0;
       int index = 0;
       while(index1<nums1.length&&index2<nums2.length){
    	   if(nums1[index1]<nums2[index2]){
    		   num[index]=nums1[index1];
    		   index1++;
    	   }
    	   else{
    		   num[index]=nums2[index2];
    		   index2++;
    	   }
    	   index++;
       }
       while(index1<nums1.length){
    	   num[index++]=nums1[index1++];
       }
       while(index2<nums2.length){
    	   num[index++]=nums2[index2++];
       }
       if(index%2!=0){
    	   index = num.length/2;
    	   return num[index];
       }
       else{
    	   index = num.length/2;
    	   return (num[index]+num[index-1])/(double)2;
       }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值