• 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
    

    Subscribe to see which companies asked this question.

     1 class Solution {
     2 public:
     3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
     4         vector<int> addup;
     5         int tag1=0,tag2=0;
     6         while(tag1!=nums1.size() && tag2!=nums2.size())
     7         {
     8             if(nums1[tag1]<nums2[tag2])
     9             {
    10                 addup.push_back(nums1[tag1]);
    11                 tag1++;
    12             }
    13             else
    14             {
    15                 addup.push_back(nums2[tag2]);
    16                 tag2++;
    17             }
    18             //cout<<addup[addup.size()-1]<<" ";
    19         }
    20         while(tag2!=nums2.size())
    21         {
    22             addup.push_back(nums2[tag2]);
    23             tag2++;
    24         }
    25         while(tag1!=nums1.size())
    26         {
    27             addup.push_back(nums1[tag1]);
    28             tag1++;
    29         }
    30         if((tag1+tag2)%2==0) return (double(addup[(tag1+tag2)/2])+double(addup[(tag1+tag2)/2-1]))/2;
    31         else return double(addup[(tag1+tag2)/2]);
    32     }
    33 };
     
  • 相关阅读:
    JavaScript 数组操作函数--转载+格式整理
    Python之__str__类的特殊方法
    Django 模板层(Template)
    jquery基础
    Django基础(web框架)
    前端基础之JavaScript对象
    前端基础之JavaScript
    MySQL数据库之索引
    MySQL数据库之多表查询
    MySQL 数据库之单表查询
  • 原文地址:https://www.cnblogs.com/pkjplayer/p/6433035.html
Copyright © 2020-2023  润新知