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
刚看到题基本思路是将两个数据按顺序排列然后取中位数(偶数取中位两数平均数)
下面是自己的方法(姑且称之为齿轮法,也是比较传统的方法):
public double findMedianSortedArrays(int[] nums1, int[] nums2) { ArrayList<Integer> arrayList = new ArrayList<>(); int index1 = 0; int index2 = 0; for (int i =0; i< nums1.length; i++) { for (int j = index2; j < nums2.length; j++) { if (nums1[index1] <= nums2[j]) { arrayList.add(nums1[index1]); index1 ++; break; } else { arrayList.add(nums2[j]); index2 ++; } } } if(index1 < nums1.length) { for(; index1 < nums1.length; index1++){ arrayList.add(nums1[index1]); } } if(index2 < nums2.length) { for(; index2 < nums2.length; index2++){ arrayList.add(nums2[index2]); } } int totalSize = arrayList.size(); if(totalSize % 2 == 0) { return (arrayList.get(totalSize / 2 - 1) + arrayList.get(totalSize / 2)) / 2.0; } else { return arrayList.get(totalSize / 2); } }
果不其然,性能只打败了13.8%的人。
这个题目的难度是Hard,考虑了许久没有更好解决方案,所以查看官网,果然演变为数学问题,感兴趣的可以看下下面地址
参考:
https://leetcode.com/problems/median-of-two-sorted-arrays/