Median of Two Sorted Arrays
来源:互联网 发布:淘宝店铺单品分析软件 编辑:程序博客网 时间:2024/06/05 04:53
1、一提到中位数就要考虑数组的个数是奇数还是偶数;
2、涉及到排序数组的求和、求中位数这类的问题都要想到用二分法的思想;
题目:
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)).
找到两个数组所组成的数的中位数。
思路:
1、考虑特殊情况,即有一个数组为空、每个数组只有一个元素;
2、判断m+n是奇数还是偶数,然后进行递归;
3、利用二分的思路,一半一半的进行删除,令
int pa=min(k/2,n);int pb=k-pa;
用k的一半进行比较,如果前一半比较小,则肯定不符合条件,则递归find(nums1[pa],m-pa,nums2,n,k-pa)
,反之如果pb比较小则这部分肯定也不符合条件,递归find(nums1,m,nums2[pb],n-pb,k-pb)
;
代码:
class Solution {public: double find(vector<int> & nums1,int m,vector<int> & nums2,int n,int k) { if(m<n) return find( nums1,n,nums2,m,k); if(n==0) return nums2[k-1]; if(k==1) return min(nums1[0],nums2[0]); int pa=min(k/2,n); int pb=k-pa; if(nums1[pa-1]>nums2[pb-1]) return find(nums1,m,nums2+pb,n-pb,k-pb); else if(nums1[pa-1]<nums2[pb-1]) return find(nums1+pa,m-pa,nums2,n,k-pa); else return nums1[pa-1]; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m=nums1.size(); int n=nums2.size(); int total=n+m; if(total%2) return find(nums1,m,nums2,n,total/2+1); else return (find(nums1,m,nums2,n,total/2)+find(nums1,m,nums2,n,total/2+1))/2; }};
但是出现了如下的错误,不知道怎么改,希望大家能帮助改正;
Line 10: no matching function for call to ‘Solution::find(std::vector&, int&, __gnu_cxx::__alloc_traits
0 0
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of two sorted arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- median-of-two-sorted-arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- IOS中的类别(Category)和扩展(Extension)
- 1到100递归
- 在linux下安装配置cuda
- mac如何修改hosts?mac修改hosts图文教程
- 测试PHP扩展动态库错误
- Median of Two Sorted Arrays
- AppiumForWindows 菜鸟计划(五)uiautomatorviewer
- 设置UIButton上字体的对齐方式
- Linux系统下CUDA中的原子操作
- 链表实现多项式操
- ExtJS 的TreePanel
- hdu1044 Collect More Jewels
- 布局
- 并发概念总结