LeetCode Median of Two Sorted Arrays
2015-08-08 11:58
351 查看
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)).
Show Tags
题意:求两个有序数组的组成一个新的数组的中位数
思路:题目转换为求第k大的数。假设总个数是奇数的话,就是求第中间的数了,假设是偶数的话。就是找到两个中间的,求平均数。
求第k大的数:首先如果我们求的是两个数组A和B中第k个数。为了我们每次都能折半查找,我们比較A[k/2]和B[k/2]这两个数,如果A[k/2-1]<B[k/2-1]的话。说明的是A数组的前k/2个数字都是在最后数组的前k个中,那么就能够裁掉一点了,依次类推
Show Tags
题意:求两个有序数组的组成一个新的数组的中位数
思路:题目转换为求第k大的数。假设总个数是奇数的话,就是求第中间的数了,假设是偶数的话。就是找到两个中间的,求平均数。
求第k大的数:首先如果我们求的是两个数组A和B中第k个数。为了我们每次都能折半查找,我们比較A[k/2]和B[k/2]这两个数,如果A[k/2-1]<B[k/2-1]的话。说明的是A数组的前k/2个数字都是在最后数组的前k个中,那么就能够裁掉一点了,依次类推
class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int size = m + n; int k = (m + n + 1) / 2; if (size & 1) return findKth(A, m, B, n, k); else return (findKth(A, m, B, n, k) + findKth(A, m, B, n, k+1)) / 2; } double findKth(int A[], int m, int B[], int n, int k) { if (m > n) return findKth(B, n, A, m, k); if (m == 0) return B[k - 1]; if (k == 1) return A[0] < B[0] ? A[0] : B[0]; int index = k / 2; int left = index < m ? index : m; int right = k - left; if (A[left - 1] < B[right - 1]) return findKth(A + left, m - left, B, n, right); else if (A[left - 1] > B[right - 1]) return findKth(A, m, B + right, n - right, left); else return A[left - 1]; } };
相关文章推荐
- iOS数据库操作之FMDB框架的使用
- 567D One-Dimensional Battle Ships(set)
- Leetcode -- Roman to Integer
- linux安装jdk
- [Android Studio 权威教程]最实用的快捷键
- linux man和--help的区别
- Jquery数字上下滚动动态切换插件
- [Android Studio 权威教程]Android Studio 三种添加插件的方式
- JAVA实现EXCEL公式专题(一)——EXCEL公式分类与解析步骤
- jQuery的父,子,兄弟节点查找方法
- UVALive - 3713 Astronauts(2-SAT)
- 深拷贝和浅拷贝
- [Android Studio 权威教程]配置出“NB”的Android Studio
- [Android Studio 权威教程]离线配置SDK,创建第一个AS项目
- tomcat7.0.19虚拟目录配置
- fzu 1171 Hard to Believe, but True!
- java怎么用一行代码初始化ArrayList
- 安卓的观察者模式
- fzu 1171 Hard to Believe, but True!
- [二分] 最大化平均值