1. 程式人生 > 其它 >LeetCode-004-尋找兩個正序陣列的中位數

LeetCode-004-尋找兩個正序陣列的中位數

尋找兩個正序陣列的中位數

題目描述:給定兩個大小分別為 m 和 n 的正序(從小到大)陣列 nums1 和 nums2。請你找出並返回這兩個正序陣列的 中位數 。

示例說明請見LeetCode官網。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

解法一:有序數組合並

將2個數組按順序合併到一個大數組裡面,2個數組都只會遍歷一次。然後在大陣列中獲取中位數。

解法二:待完成

思考怎麼在 時間複雜度為 O(log (m+n))

下完成?

public class Solution {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] allNums = new int[nums1.length + nums2.length];
        int i = 0, j = 0, x = 0;
        int num1 = Integer.MAX_VALUE, num2 = Integer.MAX_VALUE;
        for (; i < nums1.length || j < nums2.length; ) {
            if (i < nums1.length) {
                num1 = nums1[i];
            }
            if (j < nums2.length) {
                num2 = nums2[j];
            }
            if (num1 < num2) {
                allNums[x] = num1;
                i++;
            } else {
                allNums[x] = num2;
                j++;
            }
            x++;
            num1 = Integer.MAX_VALUE;
            num2 = Integer.MAX_VALUE;
        }
        int count = nums1.length + nums2.length;
        if (count % 2 == 1) {
            return allNums[count / 2];
        } else {
            return ((double) (allNums[count / 2 - 1] + allNums[count / 2])) / 2;
        }
    }

    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2};
        int[] nums2 = new int[]{3, 4};
        System.out.println(findMedianSortedArrays(nums1, nums2));
    }
}