Median of Two Sorted Arrays (leetcode 4)

Version 1:

本题题意是在两个有序数组中找中间数,n 和 m 分别是两个数组nums1 和nums2 的长度,若n+m 是奇数,则中间数为中位数,若是偶数,则中间数就是中间两个数值的平均数。虽然题目要求时间复杂度为O(\log (m+n)),但是脑海最先想到的第一个版本的做法就是对前一半进行归并排序,找到中间的数,进行返回,后面一半不做处理,时间复杂度为O((m+n)/2)=O(m+n),代码和结果如下:


class Solution:
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """

        # use the merge method to sort the top (m+n)/2 element
        n = len(nums1)
        m = len(nums2) 

        # deal with the situation : one list is empty
        # the number of nums1 is even and nums2 is empty
        if m == 0 and n%2 == 0:
        	return (nums1[int((n-1)/2)] + nums1[int(n/2)])/2
        # the number of nums1 is odd and nums2 is empty
        if m == 0:
        	return nums1[int(n/2)]
        # the number of nums2 is even and nums1 is empty
        if n == 0 and m%2 == 0:
        	return (nums2[int((m-1)/2)] + nums2[int(m/2)])/2
        # the number of nums2 is odd and nums1 is empty
        if n == 0:
        	return nums2[int(m/2)]


        cur = 0
        cur_num = 0
        i = -1
        j = -1
        while cur <= int((n + m - 1)/2):
        	# nums1 and nums2 both have element
        	if (i+1) < n and (j+1) <m:
        		if nums1[i+1] > nums2[j+1]:
        			j += 1
        			cur_num = nums2[j]
        		else:
        			i += 1
        			cur_num = nums1[i]
        	# just nums1 have element
        	elif (i+1) < n:
        		i += 1
        		cur_num = nums1[i]
        	# just nums2 have element
        	else:
        		j += 1
        		cur_num = nums2[j]
        	cur += 1
        next_num = 0
        # nums1 and nums2 both have element
        if (i+1) < n and (j+1) <m:
        	next_num = min(nums1[i+1],nums2[j+1])
        # just nums1 have element
        elif (i+1) < n:
        	next_num = nums1[i+1]
        # just nums2 have element
        else:
        	next_num = nums2[j+1]
        if (n + m)%2 == 0:
        	return (cur_num + next_num) / 2
        else: 
        	return cur_num

符合要求的时间复杂度的算法暂时肝不出来,周末再看看,毕竟今儿脑子有点小忧伤。毕竟耗时太长也不是件好事,切换下一关先。顺便考虑学习下已经解题的前辈的优秀方法。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值