Leetcode 题解系列(四)
来源:互联网 发布:linux操作系统移植 编辑:程序博客网 时间:2024/05/24 06:06
23. Merge k Sorted Lists
题目要求
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题目分析
1. 暴力解法
每一次遍历K个列表,取得最大的元素并进行归并。
ListNode* mergeKLists(vector<ListNode*>& lists) { bool completed = false; ListNode *ret = nullptr, *cur = nullptr; while (!completed) { int index, max = 0; completed = true; for (int i = 0; i < lists.size(); ++i) { if (lists[i] != nullptr) { completed = false; } else { continue; } if (lists[i]->val > max) { max = lists[i]->val; index = i; } } if (cur == nullptr) { ret = cur = lists[index]; } else { cur->next = lists[index]; cur = cur->next; } lists[index] = lists[index]->next; } return ret;}
2. 使用堆进行加速
上述的方法需要进行N次的遍历,其中N为元素总数,故复杂度为
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */#include <queue>struct ListCompare { bool operator() (const ListNode* lhs, const ListNode* rhs) { return lhs->val > rhs->val; }};using pq = std::priority_queue<ListNode*, vector<ListNode*>, ListCompare>;class Solution {public: ListNode* mergeKLists(vector<ListNode*>& lists) { pq queue; for (auto node : lists) { if (node != nullptr) { queue.push(node); } } ListNode* ret = nullptr, *cur = nullptr; while (!queue.empty()) { auto one = queue.top(); queue.pop(); if (cur == nullptr) { ret = cur = one; } else { cur->next = one; cur = cur->next; } one = one->next; if (one != nullptr) queue.push(one); } return ret; }};
3. 使用分治的方法进行归并
对K个待归并的子链表进行分治归并,可以降低复杂度。
阅读全文
0 0
- Leetcode 题解系列(四)
- Leetcode 题解系列(一)
- Leetcode 题解系列(二)
- Leetcode 题解系列(三)
- Leetcode 题解系列(五)
- Leetcode 题解系列(六)
- Leetcode 题解系列(七)
- Leetcode 题解系列(八)
- Leetcode 题解系列(九)
- Leetcode 题解系列(十)
- Leetcode 题解系列(十一)
- Leetcode 题解系列(十三)
- Leetcode 题解系列(十二)
- LeetCode题解(四)
- LeetCode OJ题解系列
- LeetCode Single Number系列题解
- LeetCode题解系列--1. Two Sum
- LeetCode题解系列--5. Longest Palindromic Substring
- 如何调试python(Debugging)
- Android知识体系
- hdu 1521 指数型母函数
- C++再遇指针
- 二分查找以及改进算法
- Leetcode 题解系列(四)
- 深度探索C++模型
- 实现购物车
- 【队内胡策】2017.10.15
- STM32使用C标准库time.h里面的时间时钟函数
- java分代回收垃圾
- 【设计模式】抽象工厂模式
- Object Detection -- 论文SSD(SSD: Single Shot MultiBox Detector)解读
- JDBC