• 4. 寻找两个正序数组的中位数


     

    难度困难

    给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。

    算法的时间复杂度应该为 O(log (m+n)) 。

    示例 1:

    输入:nums1 = [1,3], nums2 = [2]
    输出:2.00000
    解释:合并数组 = [1,2,3] ,中位数 2
    

    示例 2:

    输入:nums1 = [1,2], nums2 = [3,4]
    输出:2.50000
    解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
    

    提示:

    • nums1.length == m
    • nums2.length == n
    • 0 <= m <= 1000
    • 0 <= n <= 1000
    • 1 <= m + n <= 2000
    • -106 <= nums1[i], nums2[i] <= 106
     1 class Solution {
     2 public:
     3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
     4         int m = nums1.size();
     5         int n = nums2.size();
     6         if (m+n==0) return 0;
     7         if ((m+n)%2==1) {
     8             return find_kth(nums1,nums2,0,0,(m+n)/2+1);
     9         } else {
    10             return (find_kth(nums1,nums2,0,0,(m+n)/2) + find_kth(nums1,nums2,0,0,(m+n)/2+1))/2;
    11         }
    12     }
    13     // kth == 1,2,3,4
    14     //寻找2个有序数组 合并后的第 k 大数字
    15     double find_kth(vector<int>& nums1, vector<int>& nums2, int a_start, int b_start, int kth) {
    16         if (a_start>=nums1.size()) {
    17             return nums2[b_start+kth-1];
    18         }
    19         if (b_start>=nums2.size()) {
    20             return nums1[a_start+kth-1];
    21         }
    22         if (kth == 1) {
    23             return std::min(nums1[a_start],nums2[b_start]);
    24         }
    25         int a_mid = a_start + kth/2 -1;
    26         int b_mid = b_start + kth/2 -1;
    27         if (a_mid < nums1.size() && b_mid < nums2.size()) {
    28             if (nums1[a_mid] < nums2[b_mid]) {
    29                 return find_kth(nums1,nums2,a_mid+1,b_start,kth-kth/2);
    30             } else {
    31                 return find_kth(nums1,nums2,a_start,b_mid+1,kth-kth/2);
    32             } 
    33         } else if (a_mid < nums1.size())  return find_kth(nums1,nums2,a_mid+1,b_start,kth-kth/2);
    34         else if (b_mid < nums2.size())  return find_kth(nums1,nums2,a_start,b_mid+1,kth-kth/2);
    35         else return 0;
    36     }
    37 };
  • 相关阅读:
    6.Redis 哈希(Hash)的命令
    5.redis中String类型数据操作的命令
    4.redis中的key命令
    3.redis客户端连接服务器
    Bomblab
    leetcode multiply-strings
    datalab
    leetcode max-points-on-a-line
    os
    python 实现简单的端口扫描器
  • 原文地址:https://www.cnblogs.com/zle1992/p/16077059.html
Copyright © 2020-2023  润新知