leetcode 4. Median of Two Sorted Arrays
2016-05-22 17:49
351 查看
There are two sorted arrays nums1 and nums2 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)).
求两个有序数组合并后的中位数,要求时间复杂度为O(log(m+n))
size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
求两个有序数组合并后的中位数,要求时间复杂度为O(log(m+n))
package problems.algorithms; /** * There are two sorted arrays nums1 and nums2 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)). * 求两个有序数组的中位数,要求O(log(m+n)) */ public class A4MedianofTwoSortedArrays { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int k = m + n; if ((k & 1) == 1) { return findKth(nums1, 0, m, nums2, 0, n, k / 2 + 1); } else { return (double)(findKth(nums1, 0, m, nums2, 0, n, k / 2 + 1) + findKth(nums1, 0, m, nums2, 0, n, k / 2)) / 2; } } //找到两个有序数组合并后的第k个数 public int findKth(int[] a, int aStart, int aLength, int[] b, int bStart, int bLength, int kth) { if(aLength > bLength) return findKth(b, bStart, bLength, a, aStart, aLength, kth); if(aLength == 0) return b[bStart + kth - 1]; if(kth == 1) return Math.min(a[aStart], b[bStart]); int pa = Math.min(kth / 2, aLength), pb = kth - pa; if(a[aStart + pa - 1] < b[bStart + pb -1]) { return findKth(a, aStart + pa, aLength - pa, b, bStart, bLength, kth - pa); } else if(a[aStart + pa - 1] > b[bStart + pb -1]) { return findKth(a, aStart, aLength, b, bStart + pb, bLength - pb, kth - pb); } else { return a[aStart + pa - 1]; } } }
相关文章推荐
- 第11课:Spark Streaming源码解读之Driver中的ReceiverTracker架构设计以及具体实现彻底研究
- Spring-IOC-BeanFactory
- Matlab绘图高级部分
- codevs 2964公共素数因数
- vim 块选择 多行操作
- Asp.net原理理解(错误,不足继续补充)
- 实验:C++实验6-项目1
- 伤寒杂病论白话文
- PTS PCR DTS 详解
- 友盟统计平台crash信息UUID与打包时生成.dSYM的UUID不一致
- 14、Spring工具类之Resource
- MySQL - ERROR 1839
- 数据库基础知识总结
- Java--批量短连接生成工具
- 基于perl面向对象开发的微信机器人
- 用python写一个简单的推荐系统
- 13、Spring工具类的使用
- B样条基函数的定义及系数的意义
- 基于perl面向对象开发的微信机器人
- 基于perl面向对象开发的微信机器人