#leetcode#Median of Two Sorted Arrays
来源:互联网 发布:mac校园网登录 编辑:程序博客网 时间:2024/06/14 01:45
网上各种各样的解答, 还是code ganker大牛的思路最简单明了。
这里handle了一下invalid input,
用找 kth element of sorted arrays的思路, 所以每次递归k - posA 或者 k - posB也就不难理解了, 找第k个元素么, 砍掉小的半边, 就把砍掉的个数减去, 而砍掉大得部分的时候无需对k进行修改。
if(numA > numB){ return helper(B, A, startB, endB, startA, endA, k); }限定了A是长度较短的那个, 所以确定positionA的时候要考虑A的长度比 k/2 小的情况。
时间复杂度O(log(m + n))
空间复杂度递归栈的大小 O(log(m+n))
public class Solution { public double findMedianSortedArrays(int[] A, int[] B) { if(A == null || B == null){ throw new IllegalArgumentException("invalid input"); } int lenA = A.length; int lenB = B.length; int len = lenA + lenB; if(len % 2 == 0){ double r1 = (double)helper(A, B, 0, lenA - 1, 0, lenB - 1, len / 2); double r2 = (double)helper(A, B, 0, lenA - 1, 0, lenB - 1, len / 2 + 1); return (r1 + r2) / 2; } return (double)helper(A, B, 0, lenA - 1, 0, lenB - 1, len / 2 + 1); } private int helper(int[] A, int[] B, int startA, int endA, int startB, int endB, int k){ int numA = endA - startA + 1; int numB = endB - startB + 1; if(numA > numB){ return helper(B, A, startB, endB, startA, endA, k); } if(numA <= 0){ return B[startB + k - 1]; } if(k == 1){ return Math.min(A[startA], B[startB]); } int posA = Math.min(numA, k / 2); int posB = k - posA; if(A[startA + posA - 1] < B[startB + posB - 1]){ return helper(A, B, startA + posA, endA, startB, startB + posB - 1, k - posA); }else{ return helper(A, B, startA, startA + posA - 1, startB + posB, endB, k - posB); } }}
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
- powerpc 设备树dts 详解
- 安卓4.4限制外置SD卡写入权限的破解方法
- probit logit
- spark:SparkSQL应用--46
- Program Pack
- #leetcode#Median of Two Sorted Arrays
- Activiti5.16.4部署小记
- <数据结构学习与实验指导>2-2数组元素循环右移问题
- eclipse安装反编译插件
- linux基础命令
- 面试被问长处和弱点就要这么答!
- windows下python安装Numpy、Scipy、matplotlib模块
- linux 根据时间筛选删除文件
- asp.net 将本地excel表导入网页 并在gridview中显示