@@ -7,18 +7,18 @@ public static class Solution1 {
7
7
/**
8
8
* My very original solution, but verbose.
9
9
*/
10
- public ListNode [] splitListToParts (ListNode root , int k ) {
11
- int len = getLength (root );
10
+ public ListNode [] splitListToParts (ListNode head , int k ) {
11
+ int len = getLength (head );
12
12
int aveSize = len / k ;
13
13
int extra = len % k ;
14
14
ListNode [] result = new ListNode [k ];
15
15
for (int i = 0 ; i < k ; i ++) {
16
- result [i ] = root ;
16
+ result [i ] = head ;
17
17
int aveSizeTmp = aveSize ;
18
18
aveSizeTmp += extra -- > 0 ? 1 : 0 ;
19
19
int aveSizeTmp2 = aveSizeTmp ;
20
20
while (aveSizeTmp -- > 0 ) {
21
- root = root .next ;
21
+ head = head .next ;
22
22
}
23
23
if (result [i ] != null ) {
24
24
ListNode tmp = result [i ];
@@ -46,17 +46,17 @@ public static class Solution2 {
46
46
/**
47
47
* More concise version
48
48
*/
49
- public ListNode [] splitListToParts (ListNode root , int k ) {
50
- int len = getLength (root );
49
+ public ListNode [] splitListToParts (ListNode head , int k ) {
50
+ int len = getLength (head );
51
51
int aveSize = len / k ;
52
52
int extra = len % k ;
53
53
ListNode [] result = new ListNode [k ];
54
54
ListNode prev = null ;
55
55
for (int i = 0 ; i < k ; i ++, extra --) {
56
- result [i ] = root ;
56
+ result [i ] = head ;
57
57
for (int j = 0 ; j < aveSize + (extra > 0 ? 1 : 0 ); j ++) {
58
- prev = root ;
59
- root = root .next ;
58
+ prev = head ;
59
+ head = head .next ;
60
60
}
61
61
if (prev != null ) {
62
62
prev .next = null ;
@@ -75,4 +75,44 @@ private int getLength(ListNode root) {
75
75
return len ;
76
76
}
77
77
}
78
+
79
+ public static class Solution3 {
80
+ /**
81
+ * My original solution on 9/29/2021.
82
+ */
83
+ public ListNode [] splitListToParts (ListNode head , int k ) {
84
+ ListNode [] ans = new ListNode [k ];
85
+ int size = 0 ;
86
+ ListNode tmp = head ;
87
+ while (tmp != null ) {
88
+ tmp = tmp .next ;
89
+ size ++;
90
+ }
91
+ int minSize = size / k ;
92
+ int remainder = size % k ;
93
+ int i = 0 ;
94
+ if (head == null ) {
95
+ while (i < k ) {
96
+ ans [i ++] = null ;
97
+ }
98
+ }
99
+ while (i < k ) {
100
+ ListNode node = head ;
101
+ tmp = node ;
102
+ int len = minSize ;
103
+ if (remainder > 0 ) {
104
+ remainder --;
105
+ len ++;
106
+ }
107
+ while (len -- > 1 ) {
108
+ tmp = tmp .next ;
109
+ }
110
+ head = tmp .next ;
111
+ tmp .next = null ;
112
+ ans [i ] = node ;
113
+ i ++;
114
+ }
115
+ return ans ;
116
+ }
117
+ }
78
118
}
0 commit comments