zoukankan      html  css  js  c++  java
  • Leetcode: Median of Two Sorted Arrays. java.

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

    public class Solution {
        public double findMedianSortedArrays(int A[], int B[]) {
            int k = A.length + B.length;
            return k % 2 == 0 ?  (findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2 + 1) + 
            findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2)) / 2
            : findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2 + 1);
        }
        //返回两个数组中第k大的元素。
        public double findK(int a[], int s1, int e1, int b[], int s2, int e2, int k) {
            int m = e1 - s1 + 1;
            int n = e2 - s2 + 1;
            if (m > n) return findK(b, s2, e2, a, s1, e1, k); //a的长度比b的小。

    if (s1 > e1) return b[s2 + k - 1]; if (s2 > e2) return a[s1 + k - 1]; if (k == 1) return Math.min(a[s1], b[s2]); int midA = Math.min(k/2, m), midB = k - midA; //假设a的第midA大的元素比b的第midB大的元素小, //那么删掉a的前midA个元素,在剩余的数中找第k-midA大的。 if (a[s1 + midA - 1] < b[s2 + midB - 1]) return findK(a, s1 + midA, e1, b, s2, e2, k - midA); else if (a[s1 + midA - 1] > b[s2 + midB - 1]) return findK(a, s1, e1, b, s2 + midB, e2, k - midB); else return a[s1 + midA - 1]; } }



  • 相关阅读:
    Vue学习手记01-安装和项目创建
    [Powershell] FTP Download File
    [PowerShell] Backup Folder and Files Across Network
    SSRS 请求并显示SharePoint人员和组字段
    Beta 冲刺 (2/7)
    Beta 冲刺 (1/7)
    BETA 版冲刺前准备
    事后诸葛亮
    Alpha 答辩总结
    α冲刺 (10/10)
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5151345.html
Copyright © 2011-2022 走看看