美文网首页
寻找两个有序数组的中位数

寻找两个有序数组的中位数

作者: 二进制的二哈 | 来源:发表于2019-11-25 17:26 被阅读0次

    题目来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays

    给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。

    请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

    你可以假设 nums1 和 nums2 不会同时为空。

    示例 1:

    nums1 = [1, 3]
    nums2 = [2]
    
    则中位数是 2.0
    示例 2:
    
    nums1 = [1, 2]
    nums2 = [3, 4]
    
    则中位数是 (2 + 3)/2 = 2.5
    

    Java代码:

    class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int totalLen = nums1.length + nums2.length;
            //判断是不是奇数
            boolean odd = totalLen%2 == 1;
            int[] newNums = new int[totalLen];
            int count = 0;
            int index1 = 0;
            int index2 = 0;
            while(index1 < nums1.length || index2 < nums2.length){
                if(index1 >= nums1.length){
                    newNums[count] = nums2[index2];
                    index2++;
                }else if(index2 >= nums2.length){
                    newNums[count] = nums1[index1];
                    index1++;
                }else{
                    int val1 = nums1[index1];
                    int val2 = nums2[index2];
                    if(val1 < val2){
                        newNums[count] = val1;
                        index1++;
                    }else{
                        newNums[count] = val2;
                        index2++;
                    }
                }
    
                if(odd && count == totalLen/2){
                    return newNums[count];
                }
                if(!odd && count == totalLen/2){
                    return (newNums[count-1] + newNums[count])/2.0;
    
                }
                count++;
            }
            return 0;
    
        }
    }
    

    相关文章

      网友评论

          本文标题:寻找两个有序数组的中位数

          本文链接:https://www.haomeiwen.com/subject/atpjwctx.html