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.

    method 1: use PriorityQueue (simple)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode mergeKLists(List<ListNode> lists) {
            ListNode newHead = new ListNode(0);
    		ListNode currentNode = newHead;
    		if(lists.size() > 0){
    			PriorityQueue<ListNode> nodes = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>(){
    			    	public int compare(ListNode l, ListNode n){
    		                return Integer.compare(l.val, n.val);    
                        }    
    			});
    			for(int i = 0; i < lists.size(); ++i)
    			    if(lists.get(i) != null) 
    				    nodes.add(lists.get(i));
    			
    			while(!nodes.isEmpty()){
    				ListNode nodeToSort = nodes.poll();
    				if(nodeToSort.next != null)
    					nodes.add(nodeToSort.next);
    				currentNode.next = nodeToSort;
    				currentNode = currentNode.next;
    			}
    		}
    		return newHead.next;
        }
    }
    

      

      

    method 2: merge 2 lists each step.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode mergeKLists(ArrayList<ListNode> lists) {
            ListNode head = null;
    		if(!lists.isEmpty()){
    			while(lists.size() > 1){
    				ListNode first = lists.remove(0);
    				ListNode second = lists.remove(0);
    				ListNode newNode = merge2Lists(first, second);
    				lists.add(0, newNode);
    			}
    		    head = lists.get(0);
    		}
    		return head;
        }
    	
    	public ListNode merge2Lists(ListNode first, ListNode second){
    		ListNode head = new ListNode(0);
    		ListNode nextNode = head;
    		while(first != null && second != null){
    			if(first.val <= second.val){
    				nextNode.next = first;
    				first = first.next;
    				nextNode = nextNode.next;
    			}
    			else{
    				nextNode.next = second;
    				second = second.next;
    				nextNode = nextNode.next;
    			}
    		}
    		if(first == null)
    			nextNode.next = second;
    		else
    			nextNode.next = first;
    		head = head.next;
    		return head;
        }
    }
    

      

  • 相关阅读:
    Vue.js 监听属性
    class 属性绑定
    《规划极限编程》阅读笔记03
    原型模式——C++实现
    原型模式——Java实现
    建造者模式——C++实现
    建造者模式——java实现
    抽象工厂模式——C++实现
    抽象工厂模式——java实现
    软件工程 开发模型
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3542331.html
Copyright © 2011-2022 走看看