• 19.1.19 [LeetCode4]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
     1 class Solution {
     2 public:
     3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
     4         int m = nums1.size(), n = nums2.size();
     5         int idx1 = (m + n + 1) / 2, idx2 = (m + n + 2) / 2;
     6         return (findkth(nums1, 0, nums2, 0, idx1) + findkth(nums1, 0, nums2, 0, idx2)) / 2.0;
     7     }
     8     int findkth(vector<int>&nums1, int i, vector<int>&nums2, int j, int k) {
     9         if (i >= nums1.size())return nums2[j + k - 1];
    10         if (j >= nums2.size())return nums1[i + k - 1];
    11         if (k == 1)return min(nums1[i], nums2[j]);
    12         int midval1 = (i + k / 2 <= nums1.size()) ? nums1[i + k / 2 - 1] : 9999999;
    13         int midval2 = (j + k / 2 <= nums2.size()) ? nums2[j + k / 2 - 1] : 9999999;
    14         if (midval1 < midval2)
    15             return findkth(nums1, i + k / 2, nums2, j, k - k / 2);
    16         return findkth(nums1, i, nums2, j + k / 2, k - k / 2);
    17     }
    18 };
    View Code

    有几个点:

    1.求中位数是求整个数组的第 (m+n+1)/2 和 (m+n+2)/2 个数的平均值

    2.使用奇妙的递归二分查找两个数组中的第k大数

    3.注意数组边界判断

    注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
  • 相关阅读:
    如何使用Linux命令实时查看最新的日志信息
    什么是缺陷(bug)
    APP 崩溃测试点小结
    软件测试之权限测试
    web安全测试之 xss攻击
    URL详谈
    随机生成名字或短句代码机
    JAVA环境变量配置
    Properties类与读取properties文件
    JAVA 打印九九乘法表
  • 原文地址:https://www.cnblogs.com/yalphait/p/10291218.html
Copyright © 2020-2023  润新知