Skip to content

Commit f25113d

Browse files
[N-0] refactor 725
1 parent e58345c commit f25113d

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/main/java/com/fishercoder/solutions/_725.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,36 @@ private int getLength(ListNode root) {
7575
return len;
7676
}
7777
}
78+
79+
public static class Solution2 {
80+
/**More concise version*/
81+
public ListNode[] splitListToParts(ListNode root, int k) {
82+
int len = getLength(root);
83+
int aveSize = len / k;
84+
int extra = len % k;
85+
ListNode[] result = new ListNode[k];
86+
ListNode prev = null;
87+
for (int i = 0; i < k; i++, extra--) {
88+
result[i] = root;
89+
for (int j = 0; j < aveSize + (extra > 0 ? 1 : 0); j++) {
90+
prev = root;
91+
root = root.next;
92+
}
93+
if (prev != null) {
94+
prev.next = null;
95+
}
96+
}
97+
return result;
98+
}
99+
100+
private int getLength(ListNode root) {
101+
int len = 0;
102+
ListNode tmp = root;
103+
while (tmp != null) {
104+
len++;
105+
tmp = tmp.next;
106+
}
107+
return len;
108+
}
109+
}
78110
}

src/test/java/com/fishercoder/_725Test.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@
88

99
public class _725Test {
1010
private static _725.Solution1 solution1;
11+
private static _725.Solution2 solution2;
1112
private static ListNode root;
1213
private static int k;
1314
private static ListNode[] actual;
1415

1516
@BeforeClass
1617
public static void setup() {
1718
solution1 = new _725.Solution1();
19+
solution2 = new _725.Solution2();
1820
}
1921

2022
@Test
@@ -37,4 +39,24 @@ public void test2() {
3739
}
3840
}
3941

42+
@Test
43+
public void test3() {
44+
root = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3});
45+
k = 5;
46+
actual = solution2.splitListToParts(root, k);
47+
for (ListNode head : actual) {
48+
ListNode.printList(head);
49+
}
50+
}
51+
52+
@Test
53+
public void test4() {
54+
root = LinkedListUtils.contructLinkedList(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
55+
k = 3;
56+
actual = solution2.splitListToParts(root, k);
57+
for (ListNode head : actual) {
58+
ListNode.printList(head);
59+
}
60+
}
61+
4062
}

0 commit comments

Comments
 (0)