LeetCode进阶之路(Median of Two Sorted Arrays)

本文介绍了一种寻找两个有序数组中位数的方法,通过将两数组合并并排序后,根据数组长度的奇偶性来确定中位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)).

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

思路很简单,把两个数组的数字全部放到List里面,排序,偶数个就输出中间两个和的一半,奇数就输出中间一个。

public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
		 	List<Integer> list = new ArrayList<Integer>();
		 	for(int i = 0;i<nums1.length;i++){
		 		list.add(nums1[i]);
		 	}
		 	
		 	for(int i = 0;i<nums2.length;i++){
		 		list.add(nums2[i]);
		 	}

		 	Collections.sort(list, new Comparator<Integer>() {
	            public int compare(Integer arg0, Integer arg1) {
	                return arg0.compareTo(arg1);
	            }
	        });
		 	int length = nums1.length + nums2.length;
		 	if(length%2==0){
		 		return (list.get(length/2-1) + list.get(length/2))/2.0;
		 	}else {
		 		return list.get((length+1)/2-1);
		 	}
	    }
这段时间在做前台,真是做的心累,不过有一点收获,即使没有一点前台基础,这两个星期天天啃js代码,还是能做出一个看的过去的页面,重要的还是静下来啃代码,大家智商都差不多,没有谁更聪明一些,别人能做的好看,你为什么就不行?昨天的取最长子串的题目还欠着,得抽空把它解决了,拖着拖着就忘了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值