zoukankan      html  css  js  c++  java
  • LeetCode Merge k Sorted Lists

    Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode mergeKLists(List<ListNode> lists) {
    14         if (lists == null || lists.size() == 0) {
    15             return null;
    16         }
    17         Comparator<ListNode> compare=new Comparator<ListNode>() {
    18             @Override
    19             public int compare(ListNode o1, ListNode o2) {
    20                 return o1.val - o2.val;
    21             }
    22         };
    23 
    24         PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.size(), compare);
    25         for (ListNode node : lists) {
    26             if (node != null) {
    27                 queue.add(node);
    28             }
    29         }
    30         ListNode ret = new ListNode(0);
    31         ListNode temp = ret;
    32         while (!queue.isEmpty()) {
    33             temp.next=queue.poll();
    34             temp=temp.next;
    35             if (temp.next != null) {
    36                 queue.add(temp.next);
    37             }
    38         }
    39         return ret.next;
    40     } 
    41     
    42 }
  • 相关阅读:
    An AODV Tutorial
    MFC去掉单文档的"无标题-"的方法
    win32 openss 编译
    ASP.NET实现RENREN SIG计算
    std::string str.c_str() const
    fopen
    curl with ssl support for win32
    VC++ utf8 Unicode GB2312 编码转换
    编码转换
    VirtualBox uuid冲突问题
  • 原文地址:https://www.cnblogs.com/birdhack/p/4187685.html
Copyright © 2011-2022 走看看