Leetcode 148 - Sort List(分治法)

本文介绍了一种在O(nlogn)时间内对链表进行排序的方法,采用分治策略实现归并排序。通过找到链表中点将其拆分为两部分,递归地排序后再合并,最终实现整个链表的有序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

O(nlogn)的时间和O(1)的空间内对一个链表进行排序

思路

分治法:归并排序

分治法的基本思路:Devide and Conquer

对于该题:

  1. 找到链表中点,并将其从中间拆成两条链表
  2. 对这两条链表分别进行归并排序
  3. 将这两条链表进行归并

时间复杂度:devide需要进行O(logn)次,归并的时间复杂度是O(n),因此是O(nlogn)

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* GetMid(ListNode* head) {
        if (!head) return NULL;
        ListNode* slow = head;
        ListNode* fast = head->next;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }

    ListNode* Merge(ListNode* head1, ListNode* head2) {
        ListNode* vhead = new ListNode(0);
        ListNode* now = vhead;
        while (head1 || head2) {
            if (head1 && head2) {
                if (head1->val < head2->val) {
                    now->next = head1;
                    head1 = head1->next;
                } else {
                    now->next = head2;
                    head2 = head2->next;
                }
            } else if (head1) {
                now->next = head1;
                head1 = head1->next;
            } else {
                now->next = head2;
                head2 = head2->next;
            }
            now = now->next;
        }
        ListNode* head = vhead->next;
        delete(vhead);
        return head;
    }

    ListNode* MergeSort(ListNode* head) {
        if (!(head->next)) return head;
        ListNode* mid = GetMid(head);
        ListNode* head1 = head;
        ListNode* head2 = mid->next;
        mid->next = NULL;
        head1 = MergeSort(head1);
        head2 = MergeSort(head2);
        ListNode* newhead = Merge(head1, head2);
        return newhead;
    }

    ListNode* sortList(ListNode* head) {
        if (!head) return NULL;
        return MergeSort(head);    
    }
};
### 关于分治法的经典练习题 以下是几个经典的分治法问题及其 Python 实现方式: #### 合并 K 个升序链表 此问题是 LeetCode 上的一个经典题目,可以通过分治法高效解决。 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode() current = dummy while l1 and l2: if l1.val < l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next if l1: current.next = l1 elif l2: current.next = l2 return dummy.next def mergeKLists(lists) -> ListNode: if not lists or len(lists) == 0: return None interval = 1 while interval < len(lists): for i in range(0, len(lists) - interval, interval * 2): lists[i] = mergeTwoLists(lists[i], lists[i + interval]) interval *= 2 return lists[0] if len(lists) > 0 else None ``` 上述代码通过两两合并的方式逐步减少列表数量直到只剩下一个最终结果[^2]。 --- #### 表达式求值 另一个常见的分治应用是在解析算术表达式的场景下。例如,给定字符串形式的数学表达式,返回其计算结果。 ```python def calculate(s: str) -> int: def helper(s_list): stack = [] sign = '+' num = 0 while s_list: c = s_list.pop(0) if c.isdigit(): num = num * 10 + int(c) if c == '(': num = helper(s_list) if (not c.isdigit() and c != ' ') or not s_list: if sign == '+': stack.append(num) elif sign == '-': stack.append(-num) elif sign == '*': stack[-1] = stack[-1] * num elif sign == '/': stack[-1] = int(stack[-1] / float(num)) sign = c num = 0 if c == ')': break return sum(stack) return helper(list(s.replace(' ', ''))) ``` 该函数利用栈来处理加减乘除操作符,并支持括号嵌套结构。 --- #### 排序链表 对于单链表排序问题,也可以采用分治策略完成 O(n log n) 时间复杂度下的稳定排序。 ```python def sortList(head: ListNode) -> ListNode: if not head or not head.next: return head slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next mid = slow.next slow.next = None left = sortList(head) right = sortList(mid) return mergeTwoLists(left, right) # 已定义在前面部分中的 `mergeTwoLists` 函数用于辅助此处逻辑。 ``` 这段程序实现了基于归并排序思想的操作流程。 --- #### 划分子集计数问题 最后提到的是斯特林数第二类问题——即如何划分一组元素到若干非空子集中去。这是一个典型的动态规划与递推相结合的例子。 ```python from math import comb def stirling_second_kind(n: int, m: int) -> int: if n == 0 and m == 0: return 1 if n == 0 or m == 0: return 0 return m * stirling_second_kind(n - 1, m) + stirling_second_kind(n - 1, m - 1) print(stirling_second_kind(5, 3)) # 输出应为 25 ``` 这里采用了递归方法直接调用了组合公式进行快速运算[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值