LeetCoder 4. Median of Two Sorted Arrays (有序数组合并的中位数)
来源:互联网 发布:暴力蟆蛤不可取知乎 编辑:程序博客网 时间:2024/05/16 14:07
题意
两个有序数组A,B,求两个数组合并后的中位数
思路
解法一:
使用归并排序的思路,遍历两个有序数组,然后当遍历数为我们要找到的中位数的位置的时候,即可停止。时间复杂度
解法二:
根据中位数的定义可知,中位数左边的数小于等于中位数,中位数右边的数大于等于中位数,那么我门可以将左边的数看做一个集合
假设我们分割后的序列形式为
a[0],a[1],a[2],...,a[i - 1] | a[i], a[i + 1],...,a[n - 1]b[0],b[1],b[2],...,b[j - 1] | b[j], b[j + 1],...,b[m - 1]
上面的
如果数组A为较短的数组,且当前切割点为
在我们寻找满足条件的
1.
这个时候说明我们切割点
2.
这个时候说明我们切割点
3.
这个时候说明我们找到了答案,但是需要处理一下边界情况(代码中很详细,不再赘述)
因为我们只是在一个数组中进行寻找切割点,且采用的是二分的方式,所以说时间复杂度为
结果
Your runtime beats 72.67% of cpp submissions.
代码
class Solution {public: double ans; double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int n = nums1.size(); int m = nums2.size(); ans = -1; if(n > m){ swap(n, m); findNum(nums2, nums1, 0, n, n, m, ans); }else{ findNum(nums1, nums2, 0, n, n, m, ans); } return ans; }private: void findNum(vector<int>& nums1, vector<int>& nums2, int L, int R, int n, int m, double &ans){ if(ans >= 0) return ; if(L > R) return ; int i = (L + R) / 2; int j = (n + m + 1) / 2 - i; if(i < n && nums2[j - 1] > nums1[i]){ findNum(nums1, nums2, i + 1, R, n, m, ans); } else if(i > 0 && nums1[i - 1] > nums2[j]){ findNum(nums1, nums2, L, i - 1, n, m, ans); }else{ int maxL, minR; if(i == 0) maxL = nums2[j - 1]; else if(j == 0) maxL = nums1[i - 1]; else maxL = max(nums1[i - 1], nums2[j - 1]); if((n + m) % 2 != 0){ minR = -1; }else{ if(i == n) minR = nums2[j]; else if(j == m) minR = nums1[i]; else minR = min(nums1[i], nums2[j]); } ans = (maxL + max(maxL, minR)) / 2.0; } }};
- LeetCoder 4. Median of Two Sorted Arrays (有序数组合并的中位数)
- 两个有序数组的中位数 Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays 两个有序数组的中位数
- LeetCode 4. Median of Two Sorted Arrays(两个有序数组的中位数)
- 算法练习4.Median of Two Sorted Arrays两个有序数组的中位数(递归、分治)
- Leetcode刷题记—— 4. Median of Two Sorted Arrays(两有序数组的中位数)
- 【LeetCode 4. Median of Two Sorted Arrays】两个有序数组的中位数求解
- 【LeetCode】4. Median of Two Sorted Arrays两个有序数组的中位数
- 4. Median of Two Sorted Arrays(两个有序数组的中位数)
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- Median of Two Sorted Arrays - 寻找两个有序数组的中位数(重)
- LeetCode OJ 之 Median of Two Sorted Arrays(两个有序数组的中位数)
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- 两个有序数组的中位数Median of Two Sorted Arrays(很重要)
- [Leetcode #4]Median of Two Sorted Arrays 计算两个有序数组的中位数
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- LeetCode OJ:Median of Two Sorted Arrays(两个有序数组的中位数)
- C#的WebApi 与 EasyUi的DataGrid结合生成的可分页界面
- 博为峰JavaEE技术文章 —— Hibernate 指南(4)Hbm文件
- 数位DP
- C++内置数组和array的比较
- Java Math.round()函数小结
- LeetCoder 4. Median of Two Sorted Arrays (有序数组合并的中位数)
- Okhttp源码解析1
- spring学习之@ModelAttribute运用详解
- 代码Python入门(四、条件语句)
- Dos常用命令
- 使用类-运算符重载和友元
- Cisco路由器中Telnet, Console, AUX口login命令的含义
- lintcode(401)排序矩阵中的从小到大第k个数
- linux spark分布式集群搭建图文详解