1.英文題目java
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.code
Example 1:leetcode
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:it
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
2.解題class
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)); } }
單元測試import
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); } }