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);
}
}
来源:oschina
链接:https://my.oschina.net/u/2263272/blog/2872309