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
因为这道题找的是中间的数字的和的二分一,也就是中位数,所以中位数肯定是nums1和nums2的长度的一半,也就是中间数肯定是(len1 + len2 - 1) / 2和(len1 + len2 - 1) % 2 + (len1 + len2 - 1) / 2的和的二分之一,所以解起来就很容易了,把两个数组合并成一个排序的数组,然后得到中间这个数就行。但是这道题需要做到复杂度为O(log (m+n)),而我这个算法只有O((m+n)/2)所以这个算法还是不完善的,虽然可以通过测试,目前也在思考了一个方法,就是利用比较大小的方式里判断(len1 + len2 - 1) / 2在哪个数组里面,并且确定位置,等写好了,再修改一下。
public class Solution4 { /** * 偶尔超时,中间数肯定是(len1 + len2 - 1) / 2和(len1 + len2 - 1) % 2 + (len1 + len2 - 1) / 2的和的二分之一 * * @param nums1 * @param nums2 * @return */ public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; int[] numArr = new int[len1 + len2]; int first = (len1 + len2 - 1) / 2; int last = (len1 + len2 - 1) % 2 + first; for (int i = 0, j = 0; i + j <= last; ) { if (i < len1 && j < len2) { if (nums1[i] < nums2[j]) { numArr[i + j] = nums1[i]; i++; continue; } else { numArr[i + j] = nums2[j]; j++; continue; } } if (i < len1) { numArr[i + j] = nums1[i]; i++; } if (j < len2) { numArr[i + j] = nums2[j]; j++; } } return (numArr[first] + numArr[last]) * 0.5; } }