leetcode004:Median of Two Sorted Arrays
来源:互联网 发布:java编译器 编辑:程序博客网 时间:2024/06/01 08:05
问题描述
There are two sorted arrays A and B 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)).
思路分析
用到归并排序里面的关于两个有序数组合并的思想。
- 如果两数组总数是奇数,则中位数是最中间值,偶数则为最中间两个数均值;
- 可能会出现某一数组已找完还没有到达中位数,需要继续在另一个数组上向后搜寻。
代码
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { double ans=0; int len = (m + n + 1) / 2; int flag = (m + n) % 2; //用来标记中位数是一个数还是两个数的均值(1代表一个数,0代表两数均值) int finish = 0; //用来表示寻找工作是否结束 int count = 0; int i=0,j=0; while (i < m&&j < n) { if (A[i] < B[j]) { count++; if (count == len) { ans += A[i]; if (flag) { finish = 1; break; } } if (count == len + 1){ ans += A[i]; finish = 1; break; } i++; } else { count++; if (count == len) { ans += B[j]; if (flag){ finish = 1; break; } } if (count == len + 1){ ans += B[j]; finish = 1; break; } j++; } } while (!finish&&i < m) { count++; if (count == len) { ans += A[i]; if (flag) break; } if (count == len + 1){ ans += A[i]; break; } i++; } while (!finish&&j < n) { count++; if (count == len) { ans += B[j]; if (flag) break; } if (count == len + 1){ ans += B[j]; break; } j++; } ans = flag ? ans : ans / 2; return ans; }};
0 0
- leetcode004:Median of Two Sorted Arrays
- leetcode004 Median of Two Sorted Arrays
- LeetCode004----Median of Two Sorted Arrays
- Leetcode004-Median of Two Sorted Arrays
- LeetCode004 Median of Two Sorted Arrays
- Leetcode004. 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
- 第五周 【项目3-用多文件组织多个类的程序】
- 在mysql客户端提示Access Denied的解决办法
- Hadoop2.6.0运行自带WordCount报错
- fastjson 嵌套对象,泛型的再次处理
- POJ 1321 棋盘问题(dfs)
- leetcode004:Median of Two Sorted Arrays
- 大巧不工Web前端设计修炼之道——(1)Web前端开发ABC
- 今天开始刷LeetCode
- 黑马程序员--C语言之基本语法、算法和进制
- 【SeedCoder2015年 热身题4 动态规划】贴瓷砖 (题目+答案)
- 求次数
- 第五周项目3-用多文件组织多个类的程序
- 学习2--了解Cocos2d-x整个引擎框架
- 第二章第十四题