Skip to content

Commit 7fc4926

Browse files
committed
leetcode每日一练
1 parent 735a255 commit 7fc4926

File tree

2 files changed

+95
-17
lines changed

2 files changed

+95
-17
lines changed

src/com/example/LettCode21.java

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,23 +27,6 @@ public ListNode(ListNode nextval) {
2727
ListNode(int x) {
2828
val = x;
2929
}
30-
31-
public int getVal() {
32-
return val;
33-
}
34-
35-
public void setVal(int val) {
36-
this.val = val;
37-
}
38-
39-
public ListNode getNext() {
40-
return next;
41-
}
42-
43-
public void setNext(ListNode next) {
44-
this.next = next;
45-
}
46-
4730

4831
}
4932

src/com/example/LettCode23.java

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package com.example;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.Collections;
6+
import java.util.List;
7+
8+
/**
9+
* 23. 合并K个排序链表
10+
*
11+
* 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
12+
*
13+
输入:
14+
[
15+
1->4->5,
16+
1->3->4,
17+
2->6
18+
]
19+
输出: 1->1->2->3->4->4->5->6
20+
*
21+
* @author qinxuewu
22+
* @create 19/4/21上午9:15
23+
* @since 1.0.0
24+
*/
25+
26+
27+
public class LettCode23 {
28+
29+
public static class ListNode{
30+
int val;
31+
ListNode next;
32+
ListNode(int x) {
33+
val = x;
34+
}
35+
36+
}
37+
38+
public static void main(String[] args) {
39+
ListNode head1=new ListNode(1);
40+
head1.next=new ListNode(4);
41+
head1.next.next=new ListNode(5);
42+
head1.next.next.next=null;
43+
44+
45+
ListNode head2=new ListNode(1);
46+
head2.next=new ListNode(3);
47+
head2.next.next=new ListNode(4);
48+
head2.next.next.next=null;
49+
50+
51+
ListNode head3=new ListNode(2);
52+
head3.next=new ListNode(6);
53+
head3.next.next=null;
54+
55+
ListNode [] ListNode={head1,head2,head3};
56+
LettCode23 code =new LettCode23();
57+
ListNode node=code.mergeKLists(ListNode);
58+
59+
}
60+
61+
/**
62+
* 先放入集合排序 在合并
63+
* 把每个结节点的数据取出来放入集合中 然后在排序 生成一个链表返回
64+
* @param lists
65+
* @return
66+
*/
67+
public ListNode mergeKLists(ListNode[] lists) {
68+
List<Integer> list=new ArrayList<>();
69+
for (int i = 0; i <=lists.length-1; i++) {
70+
ListNode head=lists[i];
71+
72+
while (head!=null){
73+
System.out.println(head.val);
74+
list.add(head.val);
75+
head=head.next;
76+
}
77+
}
78+
79+
if(list.size()==0){
80+
return null;
81+
}
82+
Collections.sort(list);
83+
System.out.println("排序后的list: "+Arrays.toString(list.toArray()));
84+
85+
//生成排序后的链表返回
86+
ListNode node=new ListNode(0);
87+
ListNode cur=node;
88+
for (int j = 0; j <list.size() ; j++) {
89+
int val=list.get(j);
90+
cur.next=new ListNode(val);
91+
cur=cur.next;
92+
}
93+
return node.next;
94+
}
95+
}

0 commit comments

Comments
 (0)