Leetcode4:Median of Two Sorted Arrays@Python

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


这道题给定两个由小到大已排好序的列表,将它继续由从小到大的顺序排列,并返回新列表的中间值。(要求时间复杂度不能超过O(log (m+n)))

首先,给定的两个列表都是已经排好序的,所以我们不使用几种排序算法,他们的时间复杂度都超过了log(m+n)。我们可以使用数据结构中学到的归并(MergeList)两个已排好序的链表的方法。
 1 #-*-coding:utf-8-*-
 2 
 3 class Node(object):
 4     '''
 5     定义链表的结点
 6     '''
 7     def __init__(self,val):                    
 8         self.val = val
 9         self.next = None
10         
11 class Solution(object):
12     def initlist(self,nums): 
13         '''
14         链表转换函数,传入一个列表,返回列表中元素组成的有头结点的链表
15         '''
16         l = Node(0)
17         ll = l
18         for num in nums:
19             node = Node(num)
20             ll.next = node
21             ll = ll.next
22         return l
23         
24     def findMedianSortedArrays(self, nums1, nums2):
25         """
26         :type nums1: List[int]
27         :type nums2: List[int]
28         :rtype: float
29         """
30         list1 = self.initlist(nums1)
31         list2 = self.initlist(nums2)
32         list3 = Node(0)
33         pa = list1.next
34         pb = list2.next
35         pc = list3
36         
37         while(pa and pb):
38             if(pa.val<=pb.val):
39                 pc.next = Node(pa.val)
40                 pc = pc.next
41                 pa = pa.next
42             else:
43                 pc.next = Node(pb.val)
44                 pc = pc.next
45                 pb = pb.next
46         
47         # 插入剩余段        
48         if pa:
49             pc.next = pa
50         else:
51             pc.next = pb
52         
53         # 将已排好序的链表list3转换为列表nums3    
54         nums3 = []
55         ll = list3.next
56         while(ll):
57             nums3.append(ll.val)
58             ll = ll.next
59         
60         j = len(nums3)/2
61         if len(nums3)%2==0:
62             return (nums3[j]+nums3[j-1])/2.0
63         else:
64             return nums3[j]
原文地址:https://www.cnblogs.com/mzct123/p/5898800.html