Median of Two Sorted Arrays-LeetCode#4

4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:

nums1 = [1, 3]
nums2 = [2]
The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5

思路: 两个整型数组转换为List组合后排序,取中间值

public class MedianOfTwoSortedArrays {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        for (int n1 : nums1) {
            list1.add(n1);
        }
        for (int n2 : nums2) {
            list2.add(n2);
        }
        list1.addAll(list2);
        Collections.sort(list1);
        if (list1.size() % 2 == 0){
            return (double)(list1.get(list1.size() / 2) + list1.get(list1.size() / 2 - 1)) / 2;
        }else {
            return (double)(list1.get(list1.size() / 2));
        }
    }
    public static void main(String[] args) {
        MedianOfTwoSortedArrays medianOfTwoSortedArrays = new MedianOfTwoSortedArrays();
        int[] nums1 = {};
        int[] nums2 = {3, 2};
        medianOfTwoSortedArrays.findMedianSortedArrays(nums1, nums2);
    }
}
文章已创建 108

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部