Description:
There are two sorted arrays nums1 and nums2 ofsize m and n respectively.
Find the median of the two sorted arrays. The overallrun time complexity should be O(log (m+n)).
Example1:
nums1= [1, 3]
nums2= [2]
Themedian is 2.0
Example2:
nums1= [1, 2]
nums2= [3, 4]
Themedian is (2 + 3)/2 = 2.5
Tags:Binary Search, Array, Divide and Conquer
题目解析:
排序问题,难点在于时间复杂度。
解题思路:
将两个数组结合起来并排好序,中位数取中间一个元素或两个元素的平均即可。
难点在于普通排序的时间复杂度较高。
可利用题目中信息,两个给定数据均为有序数组,来降低时间复杂度。
最先想到的就是昨天刚学到的python bisect.insort()函数。
1. Python bisect:
Complexity of bisect.insort() is O(n)
My Code:
import bisect
class Solution(object):
def findMedianSortedArrays(self,nums1,nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
size1 = len(nums1)
size2 = len(nums2)
total_size = size1+size2
if size1<size2:
tem = nums1
nums1=nums2
nums2=tem
for item in nums2:
bisect.insort(nums1,item)
if total_size%2 == 0:
return (nums1[total_size/2-1]+nums1[total_size/2])/2.0
else:
return nums1[total_size/2]
2. 试图用Java中的Array.sort()实现,但是超时了。
看到讨论区有人用这个方法,在结合两个数组的时候保证了顺序。
参考代码[1]:public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int size1 = nums1.length;
int size2 = nums2.length;
int totalSize = size1+size2;
int[] total = new int[totalSize];
// System.arraycopy(nums1, 0, total, 0, size1);
// System.arraycopy(nums2, 0, total, size1, size2);
// Arrays.sort(total);
int i = 0, j = 0,curr = 0;
while(i<size1&&j<size2){
if(nums1[i]<=nums2[j]){
total[curr++]=nums1[i++];
}else
total[curr++]=nums2[j++];
}
while(i < size1)
total[curr++]=nums1[i++];
while(j < size2)
total[curr++]=nums2[j++];
if(totalSize%2==0){
return (total[totalSize/2-1]+total[totalSize/2])/2.0;
}
else
return total[totalSize/2];
Note: 注释部分为我的代码。
3. 另一个思路是分别找出两个数组的中位数,比较大小,确定区间。还没来得及细想实现。
看到网上有人用类似的方法,用到了递归,不是很好理解。先放个链接,有空再回来看。
总结:感觉这道题其实是考察对排序的灵活掌握的。
仍需学习。共勉。
Reference:
[1]. https://discuss.leetcode.com/topic/67184/my-java-solution-easy-to-understand
[2]. https://wiki.python.org/moin/TimeComplexity
[3]. https://pymotw.com/2/bisect/
[4]. http://bigocheatsheet.com/