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]; } }



  • 相关阅读:
    CF1454F Array Partition
    leetcode1883 准时抵达会议现场的最小跳过休息次数
    leetcode1871 跳跃游戏 VII
    leetcode1872 石子游戏VIII
    CF1355C Count Triangles
    CF1245D Shichikuji and Power Grid
    CF1368C Even Picture
    CF1368D AND, OR and square sum
    CF1395C Boboniu and Bit Operations
    SpringBoot和开发热部署
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5151345.html
Copyright © 2011-2022 走看看