zoukankan      html  css  js  c++  java
  • LeetCode——Median of Two Sorted Arrays

    There are two sorted arrays A and B 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)).

    有两个已排序的数组A和B,大小为m 和 n。

    找出两数组的中位数

    时间复杂度应该为 O(log (m+n))。

    简单粗暴的方法就是把两个数组合并成一个数组,排序,取中位数。可是用不到所给的已排序,也体现不了不论什么算法的意义。时间复杂度:O((m+n)log(m+n))。(只是此方法能够通过。)

    	public static double findMedianSortedArrays(int A[], int B[]) {
    		int AB[] = new int[A.length + B.length];
    		for (int i = 0; i < A.length; i++) {
    			AB[i] = A[i];
    		}
    		for (int i = 0; i < B.length; i++) {
    			AB[A.length + i] = B[i];
    		}
    		Arrays.sort(AB);
    		double median = AB.length % 2 == 1 ? AB[AB.length >> 1] : (AB[(AB.length - 1) >> 1] + AB[AB.length >> 1]) / 2.0;
    		return median;
    	}
    还有一种思路:将此问题转换为在有序数组中寻找第K小的数的问题。直接抄了这里的实现
    	public static double findMedianSortedArrays(int[] a, int[] b) {
    		int m = a.length, n = b.length;
    		int median = (m + n) / 2;
    		if ((m + n) % 2 == 1) // Single median
    			return findKthElement(a, b, median);
    		else
    			// Average of two medians
    			return (findKthElement(a, b, median) + findKthElement(a, b,
    					median - 1)) / 2.0;
    	}
    
    	private static double findKthElement(int[] a, int[] b, int k) {
    		int m = a.length, n = b.length;
    		int aStart = 0, bStart = 0; // Keep track of the starting index of both
    									// arrays under consideration
    		int ka, kb;
    		while (true) {
    			if (aStart == m) // a is empty; find the k-th element in b
    				return b[bStart + k];
    			if (bStart == n) // b is empty; find the k-th element in a
    				return a[aStart + k];
    			if (k == 0) // Find the smallest element
    				return Math.min(a[aStart], b[bStart]);
    			// Set the indices of the elements under consideration
    			if (k == 1) { // A special case when k/2-1 < 0
    				ka = aStart;
    				kb = bStart;
    			} else { // Make sure the indices are within the boundaries
    				ka = Math.min(m - 1, aStart + k / 2 - 1);
    				kb = Math.min(n - 1, bStart + k / 2 - 1);
    			}
    
    			// Adjust k and the start index according to the relationship
    			// between a[ka] and b[kb]
    			if (a[ka] <= b[kb]) { // Any Element in a[aStart...ka] cannot be the one
    				k -= ka - aStart + 1;
    				aStart = ka + 1;
    			} else { // Any Element in b[bStart...kb] cannot be the one
    				k -= kb - bStart + 1;
    				bStart = kb + 1;
    			}
    		}
    	}


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    springboot下使用多线程
    springboot 下测试 service中的方法
    maven 将本地jar包 安装到本地仓库
    idea下http响应乱码
    使用vue-element-admin框架时如何添加多级目录
    如何在uniapp中使用mqtt
    在uniapp设计的APP中引入axios,支持cookie(真机亲测可行)
    vue中get方法如何传递数组参数
    Vue跨域访问,axios&cors
    Vue页面间传值,客户端数据存储,以及父子组件间props传值
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4840876.html
Copyright © 2011-2022 走看看