码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 4. Median of Two Sorted Arrays (java)

时间:2020-03-12 14:20:50      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:int start   boolean   array   median   dia   pre   find   lse   solution   

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        if (len1 == 0 && len2 == 0) return 0;
        
        if (len2 < len1) {
            int[] temp = nums2;
            nums2 = nums1;
            nums1 = temp;
            len1 = nums1.length;
            len2 = nums2.length;
        }
        int half = (len1 + len2 + 1) / 2;
        boolean even = ((len1 + len2) % 2) == 0 ? true : false;
        
        int start = 0;
        int end = len1;
        int apart = 0;
        int bpart = 0;
        while (start <= end) {
            apart = (start + end) / 2;
            bpart = half - apart;
            if (apart > start && nums1[apart - 1] > nums2[bpart]) end = apart - 1;
            else if (apart < end && nums1[apart] < nums2[bpart - 1]) start = apart + 1;
            else {
                int leftmax = 0;
                if (apart == 0) leftmax = nums2[bpart - 1];
                else if (bpart == 0) leftmax = nums1[apart - 1];
                else {
                    leftmax = Math.max(nums1[apart - 1], nums2[bpart - 1]);
                }
                if (!even) return leftmax;
                
                int minRight = 0;
                if (apart == len1) minRight = nums2[bpart];
                else if (bpart == len2) minRight = nums1[apart];
                else {
                    minRight = Math.min(nums2[bpart], nums1[apart]);
                }
                
                return (leftmax + minRight) / 2.0;
            }
        }
        return 0;
    }
} 
//时间复杂度: O(log(min(m, n)))
//空间复杂度: O(1)

  

leetcode 4. Median of Two Sorted Arrays (java)

标签:int start   boolean   array   median   dia   pre   find   lse   solution   

原文地址:https://www.cnblogs.com/eniac-inner/p/12468876.html

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