Merge Two Sorted Lists
刚开始看错变量类别了,还以为是string类型的,结果是listnode(链表)类型的,不过对于string类型的,还是学习到了很多python的许多函数的表达
string类型
先把代码贴出来,python代码如下:
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: str
:type l2: str
:rtype: ListNode
"""
a1 = l1.split('->')
a2 = l2.split('->')
a = list(map(int, a1 + a2))
a.sort()
b = list(map(str, a))
c = '->'.join(b)
print c
if __name__ == '__main__':
l1 = '1->2->4'
l2 = '1->3->4'
s = Solution()
s.mergeTwoLists(l1, l2)
首先对于python中字符串的分割:
l1 = '1->2->4'
a1 = l1.split('->')
#结果
a1: ['1', '2', '4']
其次是map函数的使用,它可以使得list中所有的元素按照某个函数/操作(function)进行变换
map(fund, list)
#例子
a = ['1', '2', '3']
b = list(map(int, a))
#结果
b: [1, 2, 3]
最后是对于join函数的使用:它是连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
b = ['1', '2', '3']
c = '->'.join(b)
#结果
c: '1->2->3'
ListNode 链表类型
应该是平台上自己有定义ListNode这个数据结构吧,我们可以不用管,listnode的代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = cur = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else :
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return head.next
思路:定义一个空的listnode,然后对于两个listnode,相互比较值的大小,小的加入空链表,然后往后移动,直到某一个遍历完成