4. Median of Two Sorted Arrays

2018-01-25  本文已影响0人  wtmxx
class Solution {
    public double find2ndOf4(int a,int b,int c,int d,boolean ifOdd){
        int[] array = {a,b,c,d};
        int i,j = 0;
        for(i=0;i<2;i++){
            for(j=3;j>i;j--){
                if(array[j]<array[j-1]){
                    int tmp = array[j];
                    array[j] = array[j-1];
                    array[j-1] = tmp;
                }
            }
        }
        if(ifOdd){
            return (double)array[1];
        }else{
            return ((double)array[0]+array[1])/2;
        }
    }
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        int tl = l1 + l2;
        //nums1 cursor&nums2 cursor
        int p = 0;
        int q = 0;
        //record median
        double mid = 0;
        boolean flag = true;
        if(tl%2==1){
            //target position is (t1+1)/2-2
            while(p<l1&&q<l2&&l1!=0&&l2!=0){
                if(p+q+2==(tl+1)/2){
                    int c=(p==l1-1)?Integer.MAX_VALUE:nums1[p+1];
                    int d=(q==l2-1)?Integer.MAX_VALUE:nums2[q+1];
                    mid = find2ndOf4(nums1[p],nums2[q],c,d,true);
                    flag = false;
                    break;
                }
                if(nums1[p]<=nums2[q]){
                    p++;   
                }else{
                    q++;
                }
            }
            while((flag&&p==l1)||l1==0){
                if(p+q+1==(tl+1)/2){
                    mid = nums2[q];
                    break;
                }
                q++;
            }
            while((flag&&q==l2)||l2==0){
                if(p+q+1==(tl+1)/2){
                    mid = nums1[p];
                    break;
                }
                p++;
            }
        }else{
            while(p<l1&&q<l2&&l1!=0&&l2!=0){
                if(p+q+2==tl/2+1){
                    int c=(p==l1-1)?Integer.MAX_VALUE:nums1[p+1];
                    int d=(q==l2-1)?Integer.MAX_VALUE:nums2[q+1];
                    mid = find2ndOf4(nums1[p],nums2[q],c,d,false);
                    flag = false;
                    break;
                }
                if(nums1[p]<=nums2[q]){
                    p++;
                }else{
                    q++;
                }  
            }
            while((flag&&p==l1)||l1==0){
                if(p+q+1==tl/2+1){
                    mid = l1==tl/2?((double)nums1[p-1]+nums2[q])/2:((double)nums2[q]+nums2[q-1])/2;
                    break;
                }
                q++;
            }
            while((flag&&q==l2)||l2==0){
                if(p+q+1==tl/2+1){
                    mid = l2==tl/2?((double)nums1[p]+nums2[q-1])/2:((double)nums1[p]+nums1[p-1])/2;
                    break;
                }
                p++;
            }
        }
        return mid;
    }
}
上一篇下一篇

猜你喜欢

热点阅读