zoukankan      html  css  js  c++  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)).


    解题思路:

    一看算法复杂度,就知道要用binary search, binary search 的本质是本次去一半。

    本题的本质是找第K大的数字。本题找中值,则要根据奇偶性判断是两个加起来除2还是中间那个数。

    画图解决,取A[k/2-1] 与 B[k/2-1]比较,当然先要判断它们是否存在,如果 A[k/2-1] < B[k/2-1], 那么 A[0]到A[k/2-1]里不存在target, 去掉它们。然后继续比较。

    findkth 运用递归,递归的写法注意:先写极端情况,再写一般情况。不然很可能死循环。

    注意: k - k/2 != k/2  比如 k=5 k/2 = 2  k/2+k/2 = 4 != 5


    java code: 参考九章算法

    public class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            //from time complexity, think use binary search
            int len = nums1.length + nums2.length;
            if (len % 2 == 1) {
                return findKth(nums1, 0, nums2, 0, len / 2 + 1);
            }else {
                return (findKth(nums1, 0, nums2, 0, len / 2) + findKth(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0;
            }
        }
        
        //find kth number of two sorted array
        public int findKth(int[] A, int A_start, int[] B, int B_start, int k) {
            //deal with boundary case
            if (A_start >= A.length) {
                return B[B_start + k - 1];
            }
            if (B_start >= B.length) {
                return A[A_start + k - 1];
            }
            if (k == 1) {
                return Math.min(A[A_start], B[B_start]);
            }
            //deal with general case
            int A_key = A_start + k / 2 - 1 < A.length? A[A_start + k / 2 - 1] : Integer.MAX_VALUE;
            int B_key = B_start + k / 2 - 1 < B.length? B[B_start + k / 2 - 1] : Integer.MAX_VALUE;
            if(A_key < B_key) {
                return findKth(A, A_start + k / 2, B, B_start, k - k / 2);
            }else {
                return findKth(A, A_start, B, B_start + k / 2, k - k / 2);
            }
        }
    }

    Reference:

    1. http://www.jiuzhang.com/solutions/median-of-two-sorted-arrays/

  • 相关阅读:
    ural 1028. Stars 树状数组
    hoj 1110 Simply Syntax // poj 1126 Simply Syntax
    hdu 1827 Summer Holiday // tarjan求缩点
    hoj 3005 Game Rigging 强联通分量求缩点
    hoj 2741 The Busiest Man // 强连通分支+缩点+传递闭包
    poj 2488 A Knight's Journey 回溯
    hoj 1520 The Bottom of a Graph // poj 2553 The Bottom of a Graph
    单链表的操作C语言实现(转)
    UltraEdit 提示 希望转换xxx 到DOS格式吗?
    linux 下查看服务 服务运行级别(转)
  • 原文地址:https://www.cnblogs.com/anne-vista/p/5141090.html
Copyright © 2011-2022 走看看