4. Median of Two Sorted Arrays

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容