Leetcode: Median of Two Sorted Arrays. java.
2016-01-22 15:14
615 查看
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)).
complexity should be O(log (m+n)).
public class Solution { public double findMedianSortedArrays(int A[], int B[]) { int k = A.length + B.length; return k % 2 == 0 ? (findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2 + 1) + findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2)) / 2 : findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2 + 1); } //返回两个数组中第k大的元素。 public double findK(int a[], int s1, int e1, int b[], int s2, int e2, int k) { int m = e1 - s1 + 1; int n = e2 - s2 + 1; if (m > n) return findK(b, s2, e2, a, s1, e1, k); //a的长度比b的小。 if (s1 > e1) return b[s2 + k - 1]; if (s2 > e2) return a[s1 + k - 1]; if (k == 1) return Math.min(a[s1], b[s2]); int midA = Math.min(k/2, m), midB = k - midA; //假设a的第midA大的元素比b的第midB大的元素小, //那么删掉a的前midA个元素,在剩余的数中找第k-midA大的。 if (a[s1 + midA - 1] < b[s2 + midB - 1]) return findK(a, s1 + midA, e1, b, s2, e2, k - midA); else if (a[s1 + midA - 1] > b[s2 + midB - 1]) return findK(a, s1, e1, b, s2 + midB, e2, k - midB); else return a[s1 + midA - 1]; } }
相关文章推荐
- 在SpringMVC后台控制层获取参数的方式主要有两种,一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取。这里主要讲这个注解
- java多态演示
- Struts入门
- Hibernate注解使用以及Spring整合
- 20160122--集合List
- 一个实例说明java中的list,set,map三者区别
- Java实现一致性hash算法
- spring的事物管理配置
- springMVC Hibernate Validator验证框架的使用
- [Maven实战](2)Eclipse插件m2eclipse
- java线程组
- eclipse如何能快速找到某个文件夹或者文件
- struts2 上传文件
- java实现MD5加密
- 在eclipse中如何在大量项目中查找指定文件
- javascritp学习笔记之理解构造器Function.prototype
- ant安装配置使用介绍及eclipse中使用
- java 自定义注解
- Maven项目下update maven后Eclipse报错:java.lang.ClassNotFoundException: ContextLoaderListener
- Java多线程编程中Future模式的详解<转>