LeetCode 热题 HOT 100 (017/100)【宇宙最简单版】

【链表】No. 0148 排序链表【中等】👉力扣对应题目指路

希望对你有帮助呀!!💜💜 如有更好理解的思路,欢迎大家留言补充 ~ 一起加油叭 💦
欢迎关注、订阅专栏 【力扣详解】谢谢你的支持!

题目描述:给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表

  • 【难点🔥】在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序

  • 示例 :

    输入:head = [4,2,1,3]
    输出:[1,2,3,4]

🔥 思路:归并排序(二分链表,逐层合并)

  • 可以参考下图理解 (最上面一行是原链表元素,将两两元素按序合并,最终得到最下面一行的有序链表结果)
  • 对于本题目的一般解法是用数组存储链表元素值,排序后存回链表【较容易,本文未给出】
    在这里插入图片描述

⭐⭐⭐ 题目准备之合并两个有序链表: 一定要先掌握合并两个有序链表 ❗❗❗ 放在最后面啦,供不熟悉的友友参考~


参考如上思路,给出详细步骤如下:

  • 步骤一⭐写出合并两个有序链表 h1 h2 的函数 merge 备用

    • 创建虚拟头节点 dummy_head , 逐个往后链接 h1 h2 中当前 val 更小的节点
  • 步骤二⭐用双指针法 (慢指针 slow, 快指针 fast ) 将待排序链表均分为两段

    1. fast 两倍于 slow 移动,fast 走到头后,slow 走到中部 (作为第二段 💞 的 head → part_2 )
      1. 慢指针 slow 每次往前走一步:slow = slow.next
      2. 快指针 fast 每次往前走两步:fast = fast.next.next
    2. 为了将两段断开,建立 break_point 记录第二段💞前需要断点位置
      1. 即用 break_point 追踪 slow 的前一位置
      2. 注意:如果当前只有一段 (即当前链表只有一个元素,不够分段),返回当前元素,不再往后继续
        • 本文用 break_point 来判断的
  • 步骤三⭐递归处理(也就是排序)当前的两段链表:

    1. 如果两段有序链表都非空,则调用 merge 合并
    2. 否则返回对应非空的那段
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        def traversal_sort(head):
            def merge(h1, h2):  ## 【合并两个有序链表】 # ---------------- step 1
                dummy_head = ListNode()
                current = dummy_head
                while h1 or h2:
                    if not h2 or (h1 and h1.val <= h2.val):
                        current.next = h1
                        current = h1
                        h1 = h1.next
                    else:  # not h1 or (h2 and h2.val < h1.val)
                        current.next = h2
                        current = h2
                        h2 = h2.next

                return dummy_head.next
			
			# ------------------------------------------------------- step 2
            if not head:
                return None
            slow = head
            fast = head
            break_point = None

            while fast and fast.next:
                break_point = slow  # --------------------------- step 2.2.1
                slow = slow.next  # ----------------------------- step 2.1.1
                fast = fast.next.next  # ------------------------ step 2.1.2
            
            part_1 = head
            part_2 = slow
             # -------------------------------------------------- step 2.2.2
            if not break_point: return head  ## 处理只有一个元素的情况,重要!
            break_point.next = None  ## 断开

			# ------------------------------------------------------- step 3
            part_1_result = traversal_sort(part_1)
            part_2_result = traversal_sort(part_2)
            # ----------------------------------------------------- step 3.1
            if part_1_result and part_2_result:
                return merge(part_1_result, part_2_result)
            # ----------------------------------------------------- step 3.2
            if part_1_result: return part_1_result
            if part_2_result: return part_2_result
        
        return traversal_sort(head)

⭐⭐⭐ 题目准备之合并两个有序链表:一定要先掌握合并两个有序链表 ❗❗❗

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy_head = ListNode()
        current = dummy_head
        h1, h2 = list1, list2  ## 为和本文保持一致,换名为 h1 h2
        while h1 or h2:
            if not h2 or (h1 and h1.val <= h2.val):
                current.next = h1
                current = h1
                h1 = h1.next
            else:  # not h1 or (h2 and h2.val < h1.val)
                current.next = h2
                current = h2
                h2 = h2.next

        return dummy_head.next        

希望对你有帮助呀!!💜💜 如有更好理解的思路,欢迎大家留言补充 ~ 一起加油叭 💦
🔥 LeetCode 热题 HOT 100

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值