美文网首页
4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

作者: FlynnLWang | 来源:发表于2016-10-12 03:34 被阅读0次

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.

相关文章

网友评论

      本文标题:4. Median of Two Sorted Arrays

      本文链接:https://www.haomeiwen.com/subject/zktiyttx.html