zoukankan      html  css  js  c++  java
  • 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)).

     可以用归并,但O(m+n),要求O(log(m+n)),因此转化为求前k的值,若a[k/2-1]<b[k/2-1],则a[0]-a[k/2-1]都在前k里,因此去除,继续递归。
    3种边界:(1)m=0(m为较小数组);(2)k=1;(3)a[k/2-1]==b[k/2-1];
    PS:注意判断条件,开始因为if(k=1)导致一直出错又找不出错误。
     1 class Solution {
     2 private:
     3     double findkth(vector<int>::iterator nums1, int m, vector<int>::iterator nums2, int n, int k)
     4     {
     5         if(m>n)
     6             return findkth(nums2,n,nums1,m,k);
     7         if(m==0)
     8             return *(nums2+k-1);
     9         if(k==1)
    10             return min(*nums1,*nums2);
    11         int tmpm=min(m,k/2);
    12         int tmpn=k-tmpm;
    13         if(*(nums1+tmpm-1)<*(nums2+tmpn-1))
    14         {
    15             
    16             return findkth(nums1+tmpm,m-tmpm,nums2,n,k-tmpm);
    17         }
    18         else if(nums1[tmpm-1]>nums2[tmpn-1])
    19         {
    20                 
    21                 return findkth(nums1,m,nums2+tmpn,n-tmpn,k-tmpn);
    22         }
    23         else
    24             return *(nums1+tmpm-1);
    25     }
    26 public:
    27     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    28         int m=nums1.size();
    29         int n=nums2.size();
    30         int total=m+n;
    31         vector<int>::iterator it1=nums1.begin();
    32         vector<int>::iterator it2=nums2.begin();
    33         if(total&0x1)
    34             return findkth(it1,m,it2,n,total/2+1);
    35         else
    36             return double (findkth(it1,m,it2,n,total/2)+findkth(it1,m,it2,n,total/2+1))*1.0/2;
    37     }
    38 };
  • 相关阅读:
    一道华为笔试题--内存块排序
    正则表达式
    Paxos算法的一个简单小故事
    Zookeeper中的Leader选取机制
    CCF201604-2俄罗斯方块
    Mybatis----Mapper.xml中的输入映射
    Mybatis----mybatis的全局配置文件SqlMapConfig.xml的配置
    Mybatis----开发dao
    Mybatis----入门程序
    Spring----面向切面编程和通知类型
  • 原文地址:https://www.cnblogs.com/zl1991/p/4686097.html
Copyright © 2011-2022 走看看