0
点赞
收藏
分享

微信扫一扫

NC36 在两个长度相等的排序数组中找到上中位数

罗蓁蓁 2022-02-05 阅读 72

描述

给定两个递增数组arr1和arr2,已知两个数组的长度都为N,求两个数组中所有数的上中位数。

上中位数:假设递增序列长度为n,为第n/2个数

题解:利用temp存储变量,依次找到两个数组中的较小值,并用count计数,当count==n时,返回temp。

public class Solution {
    /**
     * find median in two sorted array
     * @param arr1 int整型一维数组 the array1
     * @param arr2 int整型一维数组 the array2
     * @return int整型
     */
    public int findMedianinTwoSortedAray (int[] arr1, int[] arr2) {
        // write code here
        int n=(arr1.length+arr2.length)/2;
        if(n==1) return Math.min(arr1[0],arr2[0]);
        int count=0;
        int i=0,j=0;
        int temp=0;
        while(count!=n)
        {
            if(arr1[i]<=arr2[j]) {
                temp=arr1[i];
                i++;
                }
                else {
                temp=arr2[j];
                j++;
                }
            count++;
        }
        return temp;
    }
}
举报

相关推荐

0 条评论