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

    You may assume nums1 and nums2 cannot be both empty.

    Example 1:

    nums1 = [1, 3]
    nums2 = [2]
    
    The median is 2.0
    

    Example 2:

    nums1 = [1, 2]
    nums2 = [3, 4]
    
    The median is (2 + 3)/2 = 2.5
    

    基于kth smallest element in two sorted array

    time: O(log(M + N)), space: O(logk)  -- kth的额外空间复杂度是O(1), 调用logk次 -> O(logk)

    class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int k = (nums1.length + nums2.length) / 2;
            int m1 = kth(nums1, 0, nums2, 0, k + 1);
            if((nums1.length + nums2.length) % 2 == 0) {
                int m2 = kth(nums1, 0, nums2, 0, k);
                return (double)(m1 + m2) / 2.0;
            }
            return m1;
        }
        
        public int kth(int[] A, int aleft, int[] B, int bleft, int k) {
            if(aleft >= A.length) {
                return B[bleft + k - 1];
            }
            if(bleft >= B.length) {
                return A[aleft + k - 1];
            }
            if(k == 1) {
                return Math.min(A[aleft], B[bleft]);
            }
            
            int amid = aleft + k / 2 - 1;
            int bmid = bleft + k / 2 - 1;
            
            int aval = amid >= A.length ? Integer.MAX_VALUE : A[amid];
            int bval = bmid >= B.length ? Integer.MAX_VALUE : B[bmid];
            
            if(aval <= bval) {
                return kth(A, amid + 1, B, bleft, k - k / 2);
            } else {
                return kth(A, aleft, B, bmid + 1, k - k / 2);
            }
        }
    }
  • 相关阅读:
    单片机中的类型转换
    vs2013CCyusb报错(CyAPI.obj)
    c/c++ 去掉空格函数
    keil关于正点原子的sys.h工程报错修改
    【C语言】华软C语言程序设计复习
    c/c++中,clock函数的用法和作用
    vs mfc出现错误“MSB8301”解决办法
    vs出现“未将对象引用到实例的错误”
    keil uv5 代码格式化
    嵌入式软件面试
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10130954.html
Copyright © 2020-2023  润新知