• [LeetCode]4.寻找两个有序数组的中位数


    题目

    在这里插入图片描述

    自己的解法

       public double findMedianSortedArrays(int[] nums1, int[] nums2) {
           int[] nums = new int[nums1.length + nums2.length];
           for(int i =0; i < nums1.length; i++){
               nums[i] = nums1[i];
           } 
           for(int i = 0; i < nums2.length; i++){
               nums[nums1.length + i] = nums2[i];
           }
           Arrays.sort(nums);
           if(nums.length % 2 != 0){
               return nums[nums.length / 2];
           }else{
               return (nums[nums.length/2]+(nums[nums.length/2-1]))/2.0;
           }
        }
    }
    

    二分查找

    O(log(m+n))

    class Solution {
        public double findMedianSortedArrays(int[] A, int[] B) {
            int m = A.length;
            int n = B.length;
            if(m > n){
                //交换两个数组的顺序
                int[] tmp = A;A = B;B = tmp;
                int temp = m;m = n; n = temp; 
            }
            int iMin = 0, iMax = m, k = (m + n + 1) / 2;
            //二分查找i边界
            while(iMin <= iMax){
                int i = (iMin + iMax)/2;
                int j = k - i;
                if(i < iMax && B[j-1] > A[i]){
                    iMin = i + 1;
                }else if (i > iMin && A[i-1] > B[j]){
                    iMax = i - 1;
                }else{
                    int maxLeft = 0;
                    if(i == 0){ maxLeft = B[j - 1];}
                    else if(j == 0){ maxLeft = A[i - 1];}
                    else {maxLeft = Math.max(A[i-1],B[j-1]);}
                    if( (m + n) % 2 == 1 ){return maxLeft;}
                    int minRight = 0;
                    if(i == m){ minRight = B[j];}
                    else if(j == n){ minRight = A[i];}
                    else {minRight = Math.min(A[i],B[j]);}
    
                    return (maxLeft + minRight)/2.0;
                    }
            }
            return 0.0;
        }
    }
    

    在这里插入图片描述

  • 相关阅读:
    Linux HugePages及MySQL 大页配置
    tcp短连接TIME_WAIT问题解决方法大全
    从问题看本质: 研究TCP close_wait的内幕
    tcp_tw_recycle和tcp_timestamps的文章汇总
    MYSQL博客
    Tcp_tw_reuse、tcp_tw_recycle 使用场景及注意事项
    net.ipv4.tcp_tw_recycle
    TIME-WAIT和CLOSE-WAIT
    mysql 源码调试方法
    mysqldump 备份原理9
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860110.html
Copyright © 2020-2023  润新知