int[]数组合并&求中位数

今天开始尝试去刷leetcode,记录一下这个题目所遇到的坑。
题目要求:
**给定两个大小为 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****
代码示例:
 public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //数据判空处理
        if(nums1 == null) nums1 = new int[0];
        if(nums2 == null) nums1 = new int[0];

        int c[]= Arrays.copyOf(nums1, nums1.length+nums2.length);
        //将b数组添加到已经含有a数组的c数组中去
        System.arraycopy(nums2, 0, c, nums1.length, nums2.length);
        //对c数组进行排序
        Arrays.sort(c);

        double result = 0;
        if(c.length == 0) {

        } else if(c.length%2 == 0) {
            result = ((double) c[c.length/2] + (c.length/2-1 >= 0 ? c[c.length/2-1] : 0))/2;
        } else {
            result = c[(int)c.length/2];
        }
        return result;
    }
解题思路:
step1:将2个数组合并并排序
step2:判断数组的中位数是单个int数还是2个int数取中间值

遇到的问题:
1、数据源需要做判空;
2、2位数取中间值,需要考虑length为0的情况;
3、如果 int i = 1; 则i/2 = 0,是因为如果数据为int型,小数点后的值将被丢弃; 

猜你喜欢

转载自blog.csdn.net/weixin_44656996/article/details/87277309