• Java [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)).

    解题思路:

    看到时间复杂度的时候就知道这种应该使用二分查找法了,否则如果实现log的时间复杂度?

    思路已经有大神提供了,说的非常清楚,附上链接地址:http://my.oschina.net/jdflyfly/blog/283267

    代码如下:

    public class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    		int total = nums1.length + nums2.length;
    		if (total % 2 == 0)
    			return (findKth(nums1, 0, nums1.length - 1, nums2, 0,
    					nums2.length - 1, total / 2) + findKth(nums1, 0,
    					nums1.length - 1, nums2, 0, nums2.length - 1, total / 2 + 1)) / 2;
    		else
    			return findKth(nums1, 0, nums1.length - 1, nums2, 0,
    					nums2.length - 1, total / 2 + 1);
    
    	}
    
    	public double findKth(int[] a, int astart, int aend, int[] b,
    			int bstart, int bend, int k) {
    		if (aend - astart > bend - bstart)
    			return findKth(b, bstart, bend, a, astart, aend, k);
    		if (astart > aend)
    			return b[k - 1];
    		if (k == 1)
    			return a[astart] > b[bstart] ? b[bstart] : a[astart];
    		else {
    			int la = Math.min(k / 2, aend - astart + 1);
    			int lb = k - la;
    			if (a[astart + la - 1] == b[bstart + lb - 1])
    				return a[astart + la - 1];
    			else if (a[astart + la - 1] < b[bstart + lb - 1])
    				return findKth(a, astart + la, aend, b, bstart, bend, k - la);
    			else
    				return findKth(a, astart, aend, b, bstart + lb, bend, k - lb);
    		}
    
    	}
    }
    
  • 相关阅读:
    WCF 第二章 契约
    WCF 第二章 契约 两个单向契约VS一个双向契约
    WCF 第二章 契约 数据契约等效
    WCF 第二章 契约 双向操作
    WCF 第二章 契约 服务契约
    Java环境变量配置(Mac)
    java使用document解析xml文件
    使用JDOM解析xml文档
    使用SAX解析xml文档
    sharepoint 2007服务器场迁移到 64 位环境 ^
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455798.html
Copyright © 2020-2023  润新知