4. Median of Two Sorted Arrays

2016-10-12  本文已影响0人  FlynnLWang

Question Description

Screen Shot 2016-10-11 at 15.31.27.png

My Code

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] nums3 = new int[nums1.length + nums2.length];
        int m = nums1.length, n = nums2.length;
        for (int i = 0; i < m; i++) {
            nums3[i] = nums1[i];
        }
        for (int i = 0; i < n; i++) {
            nums3[i + nums1.length] = nums2[i];
        }
        Arrays.sort(nums3);
        int count = (m + n) / 2;
        if ((nums3.length & 1) == 1)
            return nums3[count];
        else
            return (nums3[count] + nums3[count - 1]) / 2.0;
    }
}

Test Result

Screen Shot 2016-10-11 at 15.32.16.png

Solution

Put nums1 and nums2 into nums3. Sort nums3 and get the median.

上一篇下一篇

猜你喜欢

热点阅读