• LeetCode 023 Merge k Sorted Lists


    题目要求:Merge k Sorted Lists

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

    Analysis

    The simplest solution is using PriorityQueue. The elements of the priority queue are ordered according to their natural ordering, or by a comparator provided at the construction time (in this case).

    Java:

    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.PriorityQueue;
     
    //  Definition for singly-linked list.
    class ListNode {
        int val;
        ListNode next;
     
        ListNode(int x) {
            val = x;
            next = null;
        }
    }
     
    public class Solution {
        public ListNode mergeKLists(ArrayList<ListNode> lists) {
            if (lists.size() == 0)
                return null;
     
            //PriorityQueue is a sorted queue
            PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.size(),
                    new Comparator<ListNode>() {
                        public int compare(ListNode a, ListNode b) {
                            if (a.val > b.val)
                                return 1;
                            else if(a.val == b.val)
                                return 0;
                            else 
                                return -1;
                        }
                    });
     
            //add first node of each list to the queue
            for (ListNode list : lists) {
                if (list != null)
                    q.add(list);
            }
     
            ListNode head = new ListNode(0);
            ListNode p = head; // serve as a pointer/cursor
     
            while (q.size() > 0) {
                ListNode temp = q.poll();
                //poll() retrieves and removes the head of the queue - q. 
                p.next = temp;
     
                //keep adding next element of each list
                if (temp.next != null)
                    q.add(temp.next);
     
                p = p.next;
            }
     
            return head.next;
        }
    }

    Time: log(k) * n.
    k is number of list and n is number of total elements.

  • 相关阅读:
    中綴表達式求值的兩種方法
    两次bfs求树的直径的正确性
    感染linux脚本程序技术
    C# 动态代码执行
    中秋写了个狼吃羊的智力游戏
    做一个让人喜欢的人
    MySQL数据库安全配置指南
    用 VS 2005 生成 .NET 1.1 程序
    防止入侵和攻击的主要技术措施
    .NETZ 原理分析
  • 原文地址:https://www.cnblogs.com/510602159-Yano/p/4278953.html
Copyright © 2020-2023  润新知