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

    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
    

    ==============

    找出两个数组的中位数,

    中位数的定义是明确的:按序排好的数组,array.size=n是奇数的话,第(n+1)/2个数字;否则就是第n/2和第(n+1)/2的平均数。

    ==========思路:

    划分思路,

    第一步:按照归并思路找到两个数组中的第k大

    第二步:按照计算中位数的方法,返回中位数。

    =========

    code实现,

    class Solution {
    public:
        double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
            int lengtha = nums1.size();
            int lengthb = nums2.size();
            int total = lengtha+lengthb;
            if(total & 0x1){
                return find_kth(nums1,nums2,total/2+1);
            }else{
                return (find_kth(nums1,nums2,total/2)+
                        find_kth(nums1,nums2,total/2+1))/2.0;
            }
        }
    private:
        int find_kth(vector<int> &A,vector<int> &B,int k){
            std::vector<int>::const_iterator p1 = A.begin();
            std::vector<int>::const_iterator p2 = B.begin();
            int m = 0;
            while(p1!=A.end() && p2!=B.end()){
                if(*p1<=*p2 && m==(k-1)){
                    return *p1;
                }else if(*p1>*p2 && m==(k-1)){
                    return *p2;
                }
                if(*p1<=*p2)
                    p1++;
                else
                    p2++;
                m++;
            }//while
            while(p1!=A.end()){
                if(m==(k-1)){
                    return *p1;
                }
                p1++;
                m++;
            }
            while(p2!=B.end()){
                if(m==(k-1)){
                    return *p2;
                }
                p2++;
                m++;
            }
            return -1;
        }
    };
  • 相关阅读:
    iOS 判断两个日期之间的间隔
    iOS UITextField设置placeholder颜色
    iOS 当键盘覆盖textFiled时简单的处理方法
    iOS 点击空白处收回键盘的几个简单代码
    iOS 字符串和图片互转
    JDBC连接数据库
    Java虚拟机原理和调优
    java读写文件IO
    MultipartFile 获取上传TXT文件字数
    Runtime.getRuntime().exec()实现Java调用python程序
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5612240.html
Copyright © 2011-2022 走看看