题目
- 寻找两个正序数组的中位数
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
解题
超级简单,都能看懂
我就合并数组,然后sort,有轮子为何不用(主要还是菜,而且懒,想不到也懒得想其他解题方法)
这个题有很多有意思的解法,我懒得看,不要学我
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
ArrayList<Integer> list = new ArrayList<>();
double result = 0.0;
for (int i : nums1) {
list.add(i);
}
for (int i : nums2) {
list.add(i);
}
Collections.sort(list);
int len = nums1.length+nums2.length;
int index = (len-1)/2;
if (len%2==0){
result = (list.get(index)+list.get(index+1))/2.0;
}else {
result = list.get(index);
}
return result;
}
}