leetcode python 012 hard 合并k个有序链表

Posted 蚂蚁不在线

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode python 012 hard 合并k个有序链表相关的知识,希望对你有一定的参考价值。

#[LeetCode] Merge k Sorted Lists 合并k个有序链表(升序)

import numpy as np
import time

class Node(object):
    def __init__(self,n,next_node=None):
        self.data=n
        self.next=next_node
    
class linklist(object):
    def __init__(self):
        self.head=None

    def init(self,data):
        assert type(data)==list,type(data)
        self.head=Node(data[0],None)
        p=self.head
        for i in data[1:]:
            node=Node(i)
            p.next=node
            p=p.next

    def show(self):
        l=[]
        p=self.head
        while p:
            l.append(str(p.data))
            p=p.next
        print(‘->‘.join(l))
    
def hebing(link1,link2):
    p1,p2=link1.head,link2.head
    if p1.data>p2.data:
        return hebing(link2,link1)
    while p2:
        if not p1.next and p2.next:
            p1.next=p2
            return link1
        if p1.data < p2.data and p1.next.data>p2.data:
            px=p1.next
            py=p2.next
            p1.next=p2
            p2.next=px
            p2=py
            p1=px
        elif p1.next.data<p2.data:
            p1=p1.next
    return link1

def fenzu(group):
    n=len(group)
    if n==1:
        return group[0]
    elif n==2:
        return hebing(group[0],group[1])
    else:
        return hebing(fenzu(group[:n//2]),fenzu(group[n//2:]))
l1,l2,l3=[1,3,5,9],[0,2,4,6,8,10],[3.1,5.5,15,46]
link1,link2,link3=linklist(),linklist(),linklist()
link1.init(l1)
link2.init(l2)
link3.init(l3)
fenzu([link1,link2,link3]).show()

以上是关于leetcode python 012 hard 合并k个有序链表的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 466 - Count The Repetitions - Hard ( Python)

LeetCode 479 - Largest Palindrome Product - Hard ( Python)

LeetCode887 - Super Egg Drop - Hard (Python)

leetcode_012 Integer to Roman(String,Math)

LeetCode——012 Integer to Roman

LeetCode-012-整数转罗马数字