LeetCode刷题之寻找两个正序数组的中位数

261 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。


题目描述

给定两个大小分别为 mn 的正序(从小到大)数组 nums1nums2。请你找出并返回这两个正序数组的 中位数

思路1:归并二分
  1. 利用归并思想,两个数组有序,相当于归并排序的最后一步,将左右两个数组直接遍历放到新数组中。
  2. 第一个while是当两个数组下标都没有越界的情况下:
    1. 两个数组都从左往右进行比较,较小的放到新数组中,下标加一进行下轮比较,
    2. 当其中一个数组下标越界后退出循环说明其中一个数组取完了,
    3. 所以后面两个只会执行一个,就是没有取完的数组,把它的数据遍历放到新数组中,排序就搞定了。
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int l1 = nums1.length, l2 = nums2.length;
        int l3 = l1+l2;
        int[] ans = new int[l3];
        int i = 0, j = 0, k = 0;
        while (i < l1 && j < l2) {
            ans[k++] = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++];
        }
        while (i < l1) {
            ans[k++] = nums1[i++];
        }
        while (j < l2) {
            ans[k++] = nums2[j++];
        }
        double num = 0;
        if (l3 % 2 == 0) {
            num =  (double)(ans[l3/2] + ans[l3/2-1]) / 2;
        } else {
            num = (double)ans[l3/2];
        }
        return num;
    }
}



思路2:双指针
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] result = new int[(nums1.length+nums2.length)];
        int k = 0;
        // 创建p,q两个变量充当指针
        int p = 0, q = 0;
        while (p<nums1.length && q<nums2.length){
            if (nums1[p] <= nums2[q]){
                result[k] = nums1[p];
                k++;
                p++;
            } else {
                result[k] = nums2[q];
                k++;
                q++;
            }
        }
        // 补上余下的数组元素
        while (p != nums1.length){
            result[k] = nums1[p];
            k++;
            p++;
        }
        while (q != nums2.length){
            result[k] = nums2[q];
            k++;
            q++;
        }

        int length = result.length;
        if (length % 2 == 0){
            return (double)(result[length/2] + result[length/2-1])/2;
        } else {
            return (double)result[length/2];
        }
        
    }
}