zoukankan      html  css  js  c++  java
  • [LeetCode] #4 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[k/2]<B[k/2],那么A中前k/2个元素一定小于AB混合数组的第k小的元素,所以下次只需要在A剩下的元素和B中的元素中找第(k-k/2)小的元素即可。利用迭代算法求解。其中奇数长度数组中位数只有一个,偶数长度数组中位数为其中的两个数字的平均。时间:54ms

    代码如下:

    class Solution {
    public:
        double findKSorteArrays(int A[], int m, int B[], int n, int k){
            if (m>n)
                return findKSorteArrays(B, n, A, m, k);
            if (m == 0)
                return B[k-1];
            if (k == 1)
                return min(A[0], B[0]);
            int px = min(k / 2, m), py = k - px;
            if (A[px-1] < B[py-1])
                return findKSorteArrays(A + px, m - px, B, n, k - px);
            else if (A[px-1] > B[py-1])
                return findKSorteArrays(A, m, B + py, n - py, k - py);
            else
                return A[px-1];
        }
        double findMedianSortedArrays(int A[], int m, int B[], int n) {
            int total = n + m;
            if (total & 0x1)
                return findKSorteArrays(A, m, B, n, total / 2 + 1);
            else
                return (findKSorteArrays(A, m, B, n, total / 2) + findKSorteArrays(A, m, B, n, total / 2+1))/2;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    398. Random Pick Index
    382. Linked List Random Node
    645. Set Mismatch
    174. Dungeon Game
    264. Ugly Number II
    115. Distinct Subsequences
    372. Super Pow
    LeetCode 242 有效的字母异位词
    LeetCode 78 子集
    LeetCode 404 左叶子之和
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4396391.html
Copyright © 2011-2022 走看看