zoukankan      html  css  js  c++  java
  • 4. Median of Two Sorted Arrays (C++)

    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


    答案:

    class Solution {
    public:
      double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        vector<int> myvec(nums1.size()+nums2.size());
        int t=0,i,j;
        for(i=0;i<nums1.size();i++){
          myvec[t]=nums1[i];
          t++;
        }
        for(j=0;j<nums2.size();j++){
          myvec[t]=nums2[j];
          t++;
        }
        sort(myvec.begin(),myvec.end());
        i=t/2;
        if(t%2==0){
          j=i-1;
        }else{
          j=i;
        }
        return (myvec[i]+myvec[j])/2.0;
      }
    };

  • 相关阅读:
    PHP的五大运行模式
    PHP设计模式-工厂模式
    php+redis实现消息队列
    面试题一
    Linux常用命令
    实现session在多台服务器上共享
    Memcache和redis的区别
    PHP设计模式-建造者模式
    FASTCgi和PHP-fpm关系
    安装vm虚拟机
  • 原文地址:https://www.cnblogs.com/devin-guwz/p/6480144.html
Copyright © 2011-2022 走看看