【Leetcode】Merge K Sorted Linked List

【題目】

Merge k sorted Linked Lists and return it as one sorted lists. Analyze and describe its complexity .

【思路】

leetcode clean book


【代碼】

	private static final Comparator<ListNode> listComparator = new Comparator<ListNode>(){
		public int compare(ListNode x, ListNode y){
			return x.val - y.val;
		}
	};
	
	public static ListNode mergeK(List<ListNode> list){
		if(list.isEmpty()) return null;
		Queue<ListNode> queue = new PriorityQueue<>(list.size(),listComparator);
		for(ListNode node : list){
			if(node!=null){
				queue.add(node);
			}
		}
		ListNode dummy = new ListNode(0);
		ListNode p = dummy;
		while(!queue.isEmpty()){
			ListNode node = queue.poll();
			p.next = node;
			p=p.next;
			if(node.next!=null){
				queue.add(node.next);
			}
		}
		return dummy.next;
		
		
	}

	public static ListNode mergeK2(List<ListNode> list){
		if (list == null) return null;
	int end = list.size() - 1;
	while(end > 0){
	int start = 0;
		while(start < end){
			list.set(start, merge2List(list.get(start),list.get(end)));
			start++;
			end--;
		}
	}
		return list.get(0);
	}
	
	public static ListNode merge2List(ListNode l1, ListNode l2){
		ListNode dummy = new ListNode(0);
		ListNode cur = dummy;
		 ListNode p = l1, q = l2;
		 while(p != null && q != null){
			 if(p.val > q.val ){
				 cur.next = q;
				 q = q.next;
			 }else{
				 cur.next = p;
				 p = p.next;
			 }
			 cur = cur.next;
		 }
		 if(p!=null) cur.next = p;
		 if(q!=null) cur.next = q;
		 
		 return dummy.next;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章