• Leetcode 4.两个排序数组的中位数


    两个排序数组的中位数

    给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 

    请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log (m+n)) 。

    你可以假设 nums1 和 nums2 不同时为空。

    示例 1:

    nums1 = [1, 3]

    nums2 = [2]

    中位数是 2.0

    示例 2:

    nums1 = [1, 2]

    nums2 = [3, 4]

    中位数是 (2 + 3)/2 = 2.5

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     1 class Solution {
     2     public double findMedianSortedArrays(int[] A, int[] B) {
     3         int m = A.length;
     4         int n = B.length;
     5         if (m > n) { // to ensure m<=n
     6             int[] temp = A; A = B; B = temp;
     7             int tmp = m; m = n; n = tmp;
     8         }
     9         int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2;
    10         while (iMin <= iMax) {
    11             int i = (iMin + iMax) / 2;
    12             int j = halfLen - i;
    13             if (i < iMax && B[j-1] > A[i]){
    14                 iMin = i + 1; // i is too small
    15             }
    16             else if (i > iMin && A[i-1] > B[j]) {
    17                 iMax = i - 1; // i is too big
    18             }
    19             else { // i is perfect
    20                 int maxLeft = 0;
    21                 if (i == 0) { maxLeft = B[j-1]; }
    22                 else if (j == 0) { maxLeft = A[i-1]; }
    23                 else { maxLeft = Math.max(A[i-1], B[j-1]); }
    24                 if ( (m + n) % 2 == 1 ) { return maxLeft; }
    25 
    26                 int minRight = 0;
    27                 if (i == m) { minRight = B[j]; }
    28                 else if (j == n) { minRight = A[i]; }
    29                 else { minRight = Math.min(B[j], A[i]); }
    30 
    31                 return (maxLeft + minRight) / 2.0;
    32             }
    33         }
    34         return 0.0;
    35     }
    36 }
  • 相关阅读:
    Leetcode 40. Combination Sum II
    Leetcode** 39. Combination Sum
    Leetcode** 210. Course Schedule II
    Leetcode** 207. Course Schedule
    Leetcode 257. Binary Tree Paths
    Leetcode** 131. Palindrome Partitioning
    Leetcode** 20. Valid Parentheses
    Leetcode 14. Longest Common Prefix
    dfs序 二进制优化 Codeforces Round #316 (Div. 2)D. Tree Requests
    Codeforces Round #318 D. Bear and Blocks
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10162962.html
Copyright © 2020-2023  润新知