Merge k Sorted Lists
2016-07-06 07:22
429 查看
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
Example
Given lists:
return
分析:
利用heap来保存数组中每一个list的第一个node, 当取出一个node以后,再把那个node的next node加进来,直到所有node都已被加进来。
Analyze and describe its complexity.
Example
Given lists:
[ 2->4->null, null, -1->null ],
return
-1->2->4->null.
分析:
利用heap来保存数组中每一个list的第一个node, 当取出一个node以后,再把那个node的next node加进来,直到所有node都已被加进来。
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param lists: a list of ListNode * @return: The head of one sorted list. */ public ListNode mergeKLists(List<ListNode> lists) { PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(10,new Comparator<ListNode>(){ @Override public int compare(ListNode n1, ListNode n2) { return n1.val - n2.val; } }); for(int i = 0; i < lists.size(); i++) { ListNode node = lists.get(i); if(node != null) { heap.add(node); } } ListNode head = null; ListNode cur = null; while(heap.size() > 0) { ListNode node = heap.poll(); if(head == null) { head = node; } if (cur != null) { cur.next = node; } cur = node; if(node.next != null) { heap.add(node.next); } } return head; } }
相关文章推荐
- CODEFORCES 270B Multithreading <<新闻持续更新>>
- 封装JavaBean对象
- Smallest rectangle Enclose Black Pixels
- NoSql入门和概述
- C++学习指南
- IntelliJ IDEA快捷键大全(图片)
- 3 Sum
- 3497. 水仙花数
- Swift编程规范之 Naming
- N-Queens | & N-Queens II
- leetcode-100. Same Tree c++
- 1561. PRIME
- Java中线程入门
- 1510. Mispelling
- MySQL: Tree-Hierarchical query
- mybatis日志输出
- 进程间通信:消息队列(代码实现)
- tomcat启动与Server.xml文件的解析
- 陶哲轩实分析-第18章 Lebesgue测度
- Android自带抽屉布局中NavigationView的动态生成