【Leetcode】4. Median of Two Sorted Arrays

送分小仙女□ 提交于 2019-12-07 17:33:18

1.英文题目

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

2.解题

package com.example.leetcode.hard;

public class FindMedianSortedArrays {

    public static double findMedianSortedArrays(int[] num1, int[] num2) {

        int m = num1.length;
        int n = num2.length;
        int size = m + n;
        int[] result = new int[(m + n)];
        for (int i = 0, j = 0, k = 0; i < m || j < n; k++) {
            if(i==m){
                result[k]=num2[j];
                j++;
                continue;
            }
            if(j==n){
                result[k]=num1[i];
                i++;
                continue;
            }
            if (num1[i] < num2[j]) {
                result[k] = num1[i];
                i++;
            } else {
                result[k] = num2[j];
                j++;
            }
        }
        return  (size % 2 == 1) ? result[(size - 1) / 2] : (result[size / 2-1] + result[size / 2 ]) / 2.0;
    }


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

单元测试

package com.example.leetcode.hard;

import org.junit.Assert;
import org.junit.Test;

import static com.example.leetcode.hard.FindMedianSortedArrays.findMedianSortedArrays;

public class FindMedianSortedArraysTest {


    @Test
    public void should_return_median_when_nums1_and_nums2() {
        int[] nums1 = new int[]{1, 2};
        int[] nums2 = {3, 4};
        /**
         * delta参数是误差参数,在delta允许的范围内是则认为两者是相等的
         */
        Assert.assertEquals("如果打印本信息, 证明参数不相等",2.5f,findMedianSortedArrays(nums1,nums2),0);

    }


}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!