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
方法1:这个比较常见的一种方法;先排序,再进行计算
package leetcode;
import org.junit.Test;
/**
* @author zhangyu
* @version V1.0
* @ClassName: MergeSortArray
* @Description: 这个题目在leetcode被编为hard类型,我这种做法居然还有这么高的效率,有点不太相信
* Runtime: 28 ms, faster than 86.93% of Java online submissions for Median of Two Sorted Arrays.
* @date 2018/12/7 15:12
**/
public class MergeSortArray {
@Test
public void fun() {
int[] nums1 = {1, 3};
int[] nums2 = {2, 4};
double media = getMedian(nums1, nums2);
// System.out.println(Arrays.toString(newArr));
System.out.println(media);
}
private double getMedian(int[] nums1, int[] nums2) {
double media = 0;
int[] newArr = mergeSortedArray(nums1, nums2);
if (newArr.length % 2 == 0) {
int length = newArr.length;
media = (newArr[(length - 1) / 2] + newArr[(length - 1) / 2 + 1]) / 2.0;
} else {
media = newArr[(newArr.length - 1) / 2];
}
return media;
}
public int[] mergeSortedArray(int[] nums1, int[] nums2) {
int nums1Length = nums1.length;
int nums2Length = nums2.length;
int[] newArr = new int[nums1Length + nums2Length];
int i = 0;
int j = 0;
int index = 0;
while (i < nums1Length && j < nums2Length) {
if (nums1[i] < nums2[j]) {
newArr[index++] = nums1[i];
i++;
} else {
newArr[index++] = nums2[j];
j++;
}
}
while (i < nums1Length) {
newArr[index++] = nums1[i];
i++;
}
while (j < nums2Length) {
newArr[index++] = nums2[j];
j++;
}
return newArr;
}
}
时间复杂度:O(n+m)
空间复杂度:O(n)