-
Notifications
You must be signed in to change notification settings - Fork 1
/
MedianOfTwoSortedArrays.java
44 lines (39 loc) · 1.25 KB
/
MedianOfTwoSortedArrays.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.hncboy;
import java.util.Arrays;
/**
* @author hncboy
* @date 2019/8/30 14:03
* @description 4.寻找两个有序数组的中位数
*
* 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
* 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
* 你可以假设 nums1 和 nums2 不会同时为空。
*
* 示例 1:
* nums1 = [1, 3]
* nums2 = [2]
* 则中位数是 2.0
*
* 示例 2:
* nums1 = [1, 2]
* nums2 = [3, 4]
* 则中位数是 (2 + 3)/2 = 2.5
*/
public class MedianOfTwoSortedArrays {
public static void main(String[] args) {
int[] nums1 = new int[]{1, 2};
int[] nums2 = new int[]{3, 4};
System.out.println(findMedianSortedArrays(nums1, nums2));
}
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums3 = new int[nums1.length + nums2.length];
System.arraycopy(nums1, 0, nums3, 0, nums1.length);
System.arraycopy(nums2, 0, nums3, nums1.length, nums2.length);
Arrays.sort(nums3);
if (nums3.length % 2 == 0) {
return (nums3[nums3.length / 2 - 1] + nums3[nums3.length / 2]) / 2.0;
} else {
return nums3[nums3.length / 2];
}
}
}