码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode: Median of Two Sorted Arrays

时间:2015-03-11 21:30:30      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

题目要求:

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)).

题目地址:https://leetcode.com/problems/median-of-two-sorted-arrays/

public class Solution {
    private static int find_kth(int[] A,int[] B,int k){
        //Arrays.copyOfRange(original, from, to)
        if(A.length>0)System.out.println("当前的A("+A.length+"):"+A[0]+"-->"+A[A.length-1]);
        if(B.length>0)System.out.println("当前的B("+B.length+"):"+B[0]+"-->"+B[B.length-1]);
        System.out.println("当前的K:"+k);
        if(A.length>B.length)return find_kth(B,A,k);
        if(A.length==0) return B[k-1];
        if(k==1) return (A[0]<B[0]?A[0]:B[0]);
        
        int ia=((k/2)>=(A.length)?A.length:(k/2));
        int ib=k-ia;
        System.out.println("对比的A中的"+A[ia-1]+"B中的"+B[ib-1]);
        if(A[ia-1]==B[ib-1]){
            return A[ia-1];
        }
        else if(A[ia-1]<B[ib-1]){
            int[] temp_A=Arrays.copyOfRange(A, ia, A.length);
            int[] temp_B=Arrays.copyOfRange(B, 0, ib);
            
            System.out.print("剔除A中的"+A[0]+"-->"+A[ia-1]);
            if(ib<B.length)System.out.println(";B中的"+B[ib]+"-->"+B[B.length-1]);
            return find_kth(temp_A,temp_B,k-ia);
            
        }else if(A[ia-1]>B[ib-1]){
            int[] temp_B=Arrays.copyOfRange(B, ib, B.length);
            int[] temp_A=Arrays.copyOfRange(A, 0, ia);
            if(ia<A.length)System.out.print("剔除A中的"+A[ia]+"-->"+A[A.length-1]);
            System.out.println(";B中的"+B[0]+"-->"+B[ib-1]);
            return find_kth(temp_A,temp_B,k-ib);
            
        }
        return 0;
    }
    public static double findMedianSortedArrays(int A[], int B[]) {
       int m=A.length,n=B.length;
       int total=m+n;
       if(total%2==0){
           //System.out.println("gg");
           return (find_kth(A,B,total/2)+find_kth(A,B,total/2+1))/2.0;
       }else{
           return (double)find_kth(A,B,total/2+1);
       }
        
    }
}

问题可以通用化成找出2个有序数组(A,B)的第K大元素,可以先找出A的k/2大元素与B的k/2大元素作比较,假设k/2为整数,有下列3种情况:

Ak/2>Bk/2:则必有Bk/2自身以及前面的元素不是第K大的,而且Ak/2后面的元素不包括Ak/2一定不是第K大的,可以排除。

而算法中不用k/2为整数,只用ia+ib=K即可。

leetcode: Median of Two Sorted Arrays

标签:

原文地址:http://www.cnblogs.com/charlesdoit/p/4330928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!