Given two sorted arrays nums1
and nums2
of size m
and n
respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n))
.
Example 1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
Example 2:文章来源:https://www.toymoban.com/news/detail-400785.html
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:文章来源地址https://www.toymoban.com/news/detail-400785.html
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
import java.util.*;
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
//int数组转为Integer类型数组
//将int数组转换为数值流-》流中的元素全部装箱,转换为Integer流-》将流转换为数组
Integer newNums1[] = Arrays.stream(nums1).boxed().toArray(Integer[]::new);
Integer newNums2[] = Arrays.stream(nums2).boxed().toArray(Integer[]::new);
ArrayList<Integer> integer = new ArrayList(Arrays.asList(newNums1));
integer.addAll(Arrays.asList(newNums2));
Collections.sort(integer);
DecimalFormat df=new DecimalFormat("0.0");//设置保留位数
if(integer.size()%2!=0){
return integer.get(integer.size()/2);
}else {
String s = df.format((integer.get(integer.size()/2) + integer.get(integer.size()/2 -1))/2.0);
double out = Double.parseDouble(s);
return out;
}
}
}
到了这里,关于leetcode Median of Two Sorted Arrays的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!