坚持每天刷一道题的小可爱还没有疯,依旧很可爱!

题目: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 

最简单的做法,将两个数组合并,然后找中间元素。

class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int max = ;
int m = nums1.size() + nums2.size();
int nums[m];
int i = , j = , f = ;
while(i<nums1.size() || j<nums2.size()){
int k = (i<nums1.size()?nums1[i]:max)<=(j<nums2.size()?nums2[j]:max)?(nums1[i++]):(nums2[j++]);
nums[f++] = k;
} float ans = m%==?((nums[m/]+nums[m/-])/2.0):(nums[(m-)/]);
return ans;
}
};

这个解法新开辟了一个新数组用来存放合并了的两个数组,空间复杂度为O(n+m)。运行时间88ms,击败7%的人。ps:果真菜。

提交过程中犯了一个小错误, float i = 3/2;   // i为1.0,而不是1.5   ps:这都能忘,大概上了家里蹲大学吧。。。

刚开始用的不是数组,而是vector<int>,测试的时候显示内存超出限制,一脸懵。自己在dev上跑显示std::bad_alloc。后面才知道vector里面有一个指针指向一片连续的内存空间,当空间不够装下数据时会自动申请另一片更大的空间,然后把原有数据拷贝过去,接着释放原来的那片空间;vector的内存机制

不用新开辟数组的合并解法,不用遍历两个数组,只需要遍历两个数组总长的一半,68ms,击败30%:

class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int max = ;
int m = nums1.size() + nums2.size() ;
int i = , j = , f = , k, kk;
int end = m/; //m为偶数,找到m/2和m/2-1,m为奇数,找到m/2
while(f<=end){
kk = k; //用来记录m/2-1
k = (i<nums1.size()?nums1[i]:max)<=(j<nums2.size()?nums2[j]:max)?(nums1[i++]):(nums2[j++]);
f++;
cout<<k;
}
float ans = m%==?( k+kk)/2.0:k;
return ans;
}
};

继续改进:

m为nums1的长度,n为nums2的长度,若m>n,交换两个数组。寻找i、j满足1) i+j=m-i+n-j(或者m-i+n-j+1)  2) max(nums1[i-1], nums2[j-1])<=min(nums[i],nums2[j]), 则中位数为 (max(nums1[i-1], nums2[j-1])+min(nums1[i],nums2[j]))/2(或者min(nums1[i],nums2[j])

寻找过程:

i = (nums1_l + nums1_r)/2 , j = (m+n)/2-i

if  nums1[i-1]<=nums2[j] &&  nums2[j-1]<=nums1[i]  找到答案。

if nums1[i-1] > nums2[j]     nums1_r = i;  i应该在左半边

if nums2[i-1] < nums2[j]    nums1_l = i;    i应该在右半边

class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
if (n > m) {
swap(n, m);
swap(nums1, nums2);
}
int l, r, mid, pos, id = (n + m + ) / ;
l = , r = n;
while (l <= r)
{
mid = (l + r) >> ;
pos = id - mid;
if (pos >= && mid < n && nums2[pos - ] > nums1[mid]) l = mid + ;
else if (mid >= && pos < m && nums2[pos] < nums1[mid - ]) r = mid - ;
else break;
}
double ans;
if (mid == ) ans = nums2[pos - ];
else if (pos == ) ans = nums1[mid - ];
else ans = max(nums1[mid - ], nums2[pos - ]);
if ((n + m) & ) return ans;
else
{
if (mid == n) ans = (ans + nums2[pos]) / 2.0;
else if (pos == m) ans = (ans + nums1[mid]) / 2.0;
else ans = (ans + min(nums1[mid], nums2[pos])) / 2.0;
}
return ans;
}
};

时间复杂度为O(log(min(m,n)))

C++ Leetcode Median of Two Sorted Arrays的更多相关文章

  1. LeetCode: Median of Two Sorted Arrays 解题报告

    Median of Two Sorted Arrays There are two sorted arrays A and B of size m and n respectively. Find t ...

  2. [LeetCode] 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 ...

  3. [leetcode]Median of Two Sorted Arrays @ Python

    原题地址:https://oj.leetcode.com/problems/median-of-two-sorted-arrays/ 题意:There are two sorted arrays A ...

  4. Leetcode Median of Two Sorted Arrays

    There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted ...

  5. LeetCode—— Median of Two Sorted Arrays

    Description: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the medi ...

  6. Leetcode: Median of Two Sorted Arrays. java.

    There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted ...

  7. LeetCode——Median of Two Sorted Arrays

    Question There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median o ...

  8. leetcode:Median of Two Sorted Arrays分析和实现

    这个问题的大意是提供两个有序的整数数组A与B,A与B并集的中间数.[1,3]与[2]的中间数为2,因为2能将A与B交集均分.而[1,3]与[2,4]的中间数为2.5,取2与3的平均值.故偶数数目的中间 ...

  9. LeetCode Median of Two Sorted Arrays 找中位数(技巧)

    题意: 给两个有序(升or降)的数组,求两个数组合并之后的中位数. 思路: 按照找第k大的思想,很巧妙.将问题的规模降低,对于每个子问题,k的规模至少减半. 考虑其中一个子问题,在两个有序数组中找第k ...

随机推荐

  1. Linux Shell脚本攻略:shell中各种括号()、(())、[]、[[]]、{}的作用

    技巧小结: 字符串比较用双中括号[[ ]]:算数比较用单中括号[ ]——左右留空格 算数运算用双小括号(( )) :shell命令及输出用小括号( )——左右不留空格 快速替换用花括号{ }——左右留 ...

  2. _spellmod_on_learn、_spellmod_on_remove

    _spellmod_on_learn._spellmod_on_remove,这俩表分别控制学习技能和遗忘技能时调用的GM命令.例如你制作了一个技能,学习炼金术这个专业时给玩家,遗忘炼金术这个专业时同 ...

  3. Python:ModuleNotFoundError: No module named 'windows'

    pymouse安装后,又出现了ModuleNotFoundError: No module named 'windows'的错误 解决: 下载安装pyhook:http://www.lfd.uci.e ...

  4. 异常处理.VC++

    ZC:个人这样 理解 C++的异常处理: ZC: (1).C++标准异常处理,try{}catch{} 抛异常:throw() [ 据说是包装的Windows函数RaiseException() ] ...

  5. mysql 清空表——truncate 与delete的区别

    清空表 truncate table [表名]: delete from [表名]: 注: truncate是整体删除(速度较快), delete是逐条删除(速度较慢). truncate不写服务器l ...

  6. vue中使用vw适配移动端

    推荐看看大漠老师的文章,非常的有收获 如何在Vue项目中使用vw实现移动端适配 1.首先在项目中安装依赖 npm i postcss-aspect-ratio-mini postcss-px-to-v ...

  7. 学习笔记52—coverletter

    SCI 论文投稿时需要递送一封 Cover letter.你曾经有没有过这样的经历:刚提笔准备写第一句话就陷入沉思——称呼怎么写?或许有的作者认为直接写 Dear editors 就可以了,不用和老外 ...

  8. Inception网络

    2018-12-09 19:39:38 一.1 * 1卷积 pooling可以对feature map的height,width进行修改,但是对通道数目无法修改. 1 * 1卷积可以在不改变图像大小的 ...

  9. 注册表的作用、bat文件中REG ADD命令添加注册表项以及bat

    注册表的用途与设置 注册表是windows的核心,里面储存着大量的系统信息,说白了就是一个庞大的数据库.如果你不懂什么是数据库,那没关系,不影响你了解注册表,不过最好对数据库有所了解.注册表里面所有的 ...

  10. Processing 与 C 相同和不同的地方

    Processing 与 C Processing 语言和其他语言有很多相似之处,这是它作为一种计算机语言的特征,同时,Processing 用于艺术创作,所以也有一些专用的函数. 相同的几点: 作为 ...