leetcode——Median of Two Sorted Arrays

来源:互联网 发布:snmpwalk命令查询端口 编辑:程序博客网 时间:2024/05/16 07:36

题目:

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

typedef vector<int>::iterator Iter;//寻找两个数组中的第k大的元素,k从1开始double findKth(const Iter& a, int m, const Iter& b, int n, int k)  {      //always assume that m is equal or smaller than n    if (m > n)          return findKth(b, n, a, m, k);      if (m == 0)  //数组a的长度变成0,那么直接从数组b中返回第k大的数        return b[k - 1];      if (k == 1)//k等于1的时候没法分解了          return min(a[0], b[0]);      //divide k into two parts      //为了防止越界,让pa小于等于m,由于k不一定是偶数,因此让pb = k - pa,只要保证pa + pb = k即可    int pa = min(k / 2, m), pb = k - pa;//pa和pb也是从1开始的    if (a[pa - 1] < b[pb - 1])          return findKth(a + pa, m - pa, b, n, k - pa);      else if (a[pa - 1] > b[pb - 1])          return findKth(a, m, b + pb, n - pb, k - pb);      else          return a[pa - 1];  }  class Solution {public:    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {        int m = nums1.size(), n = nums2.size();        int total = m + n;        if (total & 0x1)            return findKth(nums1.begin(), m, nums2.begin(), n, total / 2 + 1);          else              return (findKth(nums1.begin(), m, nums2.begin(), n, total / 2)                      + findKth(nums1.begin(), m, nums2.begin(), n, total / 2 + 1)) / 2;     }};


0 0
原创粉丝点击