Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit76a4eb3

Browse files
author
applewjg
committed
MergekSortedLists
Change-Id: Id61827319908b3baa24f6cb9278e3b5fc0fc917b
1 parent551e93b commit76a4eb3

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

‎MergekSortedLists.java

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 17, 2014
4+
Problem: Merge k Sorted Lists
5+
Difficulty: easy
6+
Source: https://oj.leetcode.com/problems/merge-k-sorted-lists/
7+
Notes:
8+
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
9+
10+
Solution: Find the smallest list-head first using minimum-heap(lgk).
11+
complexity: O(N*KlgK)
12+
*/
13+
14+
/**
15+
* Definition for singly-linked list.
16+
* struct ListNode {
17+
* int val;
18+
* ListNode *next;
19+
* ListNode(int x) : val(x), next(NULL) {}
20+
* };
21+
*/
22+
/**
23+
* Definition for singly-linked list.
24+
* public class ListNode {
25+
* int val;
26+
* ListNode next;
27+
* ListNode(int x) {
28+
* val = x;
29+
* next = null;
30+
* }
31+
* }
32+
*/
33+
publicclassSolution {
34+
publicListNodemergeKLists_1(List<ListNode>lists) {
35+
Comparator<ListNode>comp =newComparator<ListNode>(){
36+
publicintcompare(ListNodea,ListNodeb) {
37+
if(b.val >a.val) {
38+
return -1;
39+
}elseif(b.val <a.val){
40+
return1;
41+
}else {
42+
return0;
43+
}
44+
}
45+
};
46+
47+
Queue<ListNode>q =newPriorityQueue<ListNode>(10,comp);
48+
for (inti =0;i <lists.size(); ++i)
49+
if (lists.get(i) !=null)
50+
q.add(lists.get(i));
51+
52+
ListNodedummy =newListNode(0);
53+
ListNodecur =dummy;
54+
while (!q.isEmpty()) {
55+
ListNodenode =q.poll();
56+
cur =cur.next =node;
57+
if (node.next !=null)
58+
q.add(node.next);
59+
}
60+
returndummy.next;
61+
}
62+
ListNodemergeTwoLists(ListNodel1,ListNodel2) {
63+
ListNodehead =newListNode(0);
64+
ListNodecur =head;
65+
while (l1 !=null &&l2 !=null) {
66+
if (l1.val <l2.val) {
67+
cur.next =l1;
68+
l1 =l1.next;
69+
}else {
70+
cur.next =l2;
71+
l2 =l2.next;
72+
}
73+
cur =cur.next;
74+
}
75+
if (l1 !=null)cur.next =l1;
76+
if (l2 !=null)cur.next =l2;
77+
returnhead.next;
78+
}
79+
publicListNodemergeKLists(List<ListNode>lists) {
80+
if(lists.size()==0)returnnull;
81+
intsz =lists.size(),end =sz -1;
82+
while (end >0) {
83+
intbegin =0;
84+
while (begin <end) {
85+
ListNodenode =mergeTwoLists(lists.get(begin),lists.get(end));
86+
lists.set(begin,node);
87+
++begin; --end;
88+
}
89+
}
90+
returnlists.get(0);
91+
}
92+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp