【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
原创粉丝点击