【leetcode with java】4 Median of Two Sorted Arrays
来源:互联网 发布:最好的网络监控软件 编辑:程序博客网 时间:2024/06/08 00:16
<pre name="code" class="plain"><pre name="code" class="java"><pre name="code" class="plain"><pre name="code" class="plain">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)).Tags: Divide and Conquer, Array Binary Search
【分析】由于题目明确说明两个数组都是排好序的,首先会想到二分搜索,而这里恰好就用到了。
【上码】
public class Solution1 {/* * java中的对象作为函数参数时是引用传递,非值传递 */public double findMedianSortedArrays(int A[], int B[]) {// double median;int len = A.length + B.length;if (len % 2 == 0) {return (findKthMIn(A, 0, A.length-1, B, 0, B.length-1, len / 2) + findKthMIn(A, 0, A.length-1, B, 0, B.length-1, len / 2 + 1)) / 2;} else {return findKthMIn(A, 0, A.length-1, B, 0, B.length-1, len / 2 + 1);}// return median;}public double findKthMIn(int[] A, int aL, int aR, int[] B, int bL, int bR,int k) {if ((aR - aL) > (bR - bL)) {//使A为较短数组return findKthMIn(B, bL, bR, A, aL, aR, k);}if (aR - aL < 0) {return B[k - 1];}if (k<=1) {return Math.min(A[aL], B[bL]);}int pa = Math.min(aR-aL+1, k/2);int pb = k - pa;if (A[aL+pa-1] < B[bL+pb-1]) {return findKthMIn(A, aL+pa, aR, B, bL, bR, k-pa);}else if(A[aL+pa-1] > B[bL+pb-1]){return findKthMIn(A, aL, aR, B, bL+pb, bR, k-pb);}else {return A[aL+pa-1];}}}
0 0
- 【leetcode with java】4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays (Java)
- [LeetCode][Java] Median of Two Sorted Arrays
- Median of Two Sorted Arrays --leetcode java
- LeetCode : Median of Two Sorted Arrays [java]
- leetcode:Median of Two Sorted Arrays 【Java】
- [LeetCode]Median of Two Sorted Arrays(Java)
- leetcode Median of Two Sorted Arrays(Java)
- Leetcode-Median of Two Sorted Arrays (java)
- Leetcode 4 Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [leetcode 4] Median of Two Sorted Arrays
- LeetCode 4:《Median of Two Sorted Arrays》
- [Leetcode] 4 - Median of Two Sorted Arrays
- leetcode|4|Median of Two Sorted Arrays
- [Leetcode]4Median of Two Sorted Arrays
- Android中显示网页两种主要方式
- leetcode 日经贴,Cpp code -Linked List Cycle
- QT源码编译
- 全排列
- 全排列(含递归和非递归的解法)
- 【leetcode with java】4 Median of Two Sorted Arrays
- ZeroMemory、memset 和“={0}” 用于清零操作的区别 .
- WebView填坑——小功能篇
- 开源学习网站
- uva 1555(数学)
- Android中 扩大ImageView的点击区域
- mac 删除文件夹里所有的.svn文件
- Java 内存主要划分
- 动态内存空间的开辟与释放