leetcode -- Merge Two Sorted Lists -- 重点

https://leetcode.com/problems/merge-two-sorted-lists/

我的思路就是找到第一个j > i的,然后用pre_j串起来。然后相应地对i再做一次。这种思路不太好。

note在指针前进的时候,判断越界的语句要放在if 或者while的前半部分。
my code:

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """
        if not l1:
            return l2
        if not l2:
            return l1

        dummy_node1, dummy_node2 = ListNode(0), ListNode(0)
        dummy_node1.next, dummy_node2.next = l1, l2
        pre1, pre2 = dummy_node1, dummy_node2

        i,j = l1, l2

        count = 0
        while i and j:

            while j and j.val <= i.val:
                pre2 = j
                j = j.next
            pre2.next = i
            if not j:
                break
            while i and i.val <= j.val:
                pre1 = i
                i = i.next
            pre1.next = j
            if not i:
                break
        if l1.val >= l2.val:
            return dummy_node2.next
        else:
            return dummy_node1.next

更简单的办法应该是 用一个指针做为结果指针,像穿针引线一样,只串i和j中较小的那个。

ref: http://www.cnblogs.com/zuoyuan/p/3785479.html

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """
        if not l1:
            return l2
        if not l2:
            return l1

        dummy_node = ListNode(0)
        res = dummy_node
        i,j = l1,l2
        while i and j:

            if i.val < j.val:
                res.next = i # res指针只串较小的那个
                i = i.next
            else:
                res.next = j
                j = j.next
            res = res.next # res 总是保持在res中最大的那个点。不是i前面就是j前面

        if not i:
            res.next = j
        else:
            res.next = i
        return dummy_node.next

总结:
最终 这两种方法在leetcode 给的performance是一样的,都是58ms,都是最佳效率的办法

你可能感兴趣的:(LeetCode)