leetcode刷题之旅(4)Median of Two Sorted Arrays

题目描述

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


样例

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


思路分析

方法一是最开始的想法。暴力求解,但没注意复杂度,到n2了,运行时超时。

方法二:看到有序数组,查找某个值,自然是要用二分查找。有关二分查找,可以看这个


代码

方法一:

 public double findMedianSortedArrays(int[] nums1, int[] nums2) 
	{
		int[] a = new int[nums1.length+nums2.length];
		for(int i=0; i<nums1.length; i++)
		{
			a[i] = nums1[i];
		}
		for(int i=0; i<nums2.length; i++)
		{
			a[i+nums1.length] = nums1[i];
		}
		Arrays.sort(a);
		if(a.length%2==0)
		{
			return (a[a.length/2]+a[a.length/2-1])/2;
		}
		else
		{
			return(a[(a.length-1)/2]);
		}
    }

方法二:

public double findMedianSortedArrays(int[] nums1, int[] nums2) 
	{
		int m = nums1.length;
		int n = nums2.length;
		int l = (m+n+1)/2;
		int r = (m+n+2)/2;
		return (getkey(nums1, 0, nums2, 0, l) + getkey(nums1, 0, nums2, 0, r))/2;
    }
	public double getkey(int []a, int as, int[] b, int bs, int k)
	{
		if (as > a.length-1)   //分别考虑a,b数组为空的情况
		{
			return b[bs+k-1];
		}
		if (bs > b.length-1)
		{
			return a[as+k-1];
		}
		if (k==1)  //数组内只有一个元素的情况
		{
			return Math.min(a[as], b[as]);
		}
		
		int amid = Integer.MAX_VALUE;
		int bmid = Integer.MAX_VALUE;
		if (as+k/2-1 <a.length)
		{
			amid = a[as+k/2-1];
		}
		if (bs+k/2-1 <b.length)
		{
			bmid = b[bs+k/2-1];
		}
		
		if (amid < bmid)  //判断+递归查找
		{
			return getkey(a, as+k/2, b, bs, k-k/2);	
		}
		else
		{
			return getkey(a, as, b, bs+k/2, k-k/2);	
		}
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值