给定两个大小为 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
要求算法的时间复杂度为 O(log(m + n)),所以只能采用一次循环便利完两个数组。这里采用一个新的数组来存储,并取出中位数
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Scanner;
public class Solution {
public static void main(String args[]) throws IOException {
Scanner sc=new Scanner(System.in);
String str1=sc.nextLine();
String[] arr1= str1.split(",");
int[] num1 = new int[arr1.length];
for(int k = 0; k<num1.length;k++) {
num1[k] = Integer.parseInt(arr1[k]);
}
String str2=sc.nextLine();
String[] arr2=str2.split(",");
int num2[]=new int[arr2.length];
for(int k=0;k<num2.length;k++) {
num2[k] = Integer.parseInt(arr2[k]);
}
System.out.print(findMedianSortedArrays(num1,num2));
}
public static double findMedianSortedArrays(int[] nums1, int[] nums2){
int k=0,i=0,j=0;
double mid=0.0;
int[] num=new int[nums1.length+nums2.length];//存储和数组
while(k<(nums1.length+nums2.length)) {//遍历数组
if (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
num[k] = nums1[i];
i++;
} else {
num[k] = nums2[j];
j++;
}
} else if (i < nums1.length) {//nums2遍历完,将nums1添加到num中
num[k] = nums1[i];
i++;
} else {//同理,nums1遍历完,将nums2添加到num中
num[k] = nums2[j];
j++;
}
k++;
}
if(k%2==0){mid=(double)(num[k/2-1]+num[k/2])/2;}
else {mid=(double)num[k/2];}//求中位数
return mid;
}
}