LeetCode | Median of Two Sorted Arrays
来源:互联网 发布:如何供货给淘宝 编辑:程序博客网 时间:2024/06/05 15:21
题目:
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)).
思路:
基本思路是从两个数组中依次移除最小最大的一对数,重复操作直到两个数组共剩下1个或者2个数,即为中位数。代码:
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int left_A = 0; int right_A = m-1; int left_B = 0; int right_B = n-1; while((right_A>=left_A||right_B>=left_B)&&(getNum(left_A,right_A)+getNum(left_B,right_B))>2) { getMinVal(left_A,right_A,A)<getMinVal(left_B,right_B,B)?left_A++:left_B++; getMaxVal(left_A,right_A,A)<getMaxVal(left_B,right_B,B)?right_B--:right_A--; }; if(left_A==right_A&&left_B==right_B) { return (A[left_A]+B[left_B])/2.0; } else if(left_A==right_A) { return A[left_A]; } else if(left_B==right_B) { return B[left_B]; } else if(left_A+1==right_A) { return (A[left_A]+A[right_A])/2.0; } else if(left_B+1==right_B) { return (B[left_B]+B[right_B])/2.0; } } int getMinVal(int left, int right, int array[]) { if(left>right) return INT_MAX; else return array[left]; } int getMaxVal(int left, int right, int array[]) { if(left>right) return INT_MIN; else return array[right]; } int getNum(int left, int right) { if(left>right) { return 0; } else { return right-left+1; } }};
0 0
- LeetCode: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- leetcode Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- 【转载】【leetcode】Median of Two Sorted Arrays
- LeetCode - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- 《黑马程序员》 鼠标和键盘监听器 窗体事件 图形化管理界面 day22
- Debian ibus配置
- 我的WCF4 Rest Service及Entity Framework with POCO之旅(一)——创建一个基本的RESTful Service
- Debian安装的Chromium-browser中文显示不正常解决方法
- 黑马程序员 动态代理
- LeetCode | Median of Two Sorted Arrays
- CommonLisp环境搭建及HelloWorld
- IT零起步-CentOS6.4部署PPTPVPN服务器
- 【Gordon's Great Escape】美食大冒险第二季第一集双语字幕
- 黑马程序员 银行业务调度系统
- 黑马程序员 交通灯管理系统
- OJ中java,C++输入输出重定向的方法
- asp.net发送邮件
- UVA 11437 Triangle Fun