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

Commit 346af2d

Browse files
author
ruislan
committed
solved q725
1 parent a3af01a commit 346af2d

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

‎src/q/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,7 @@ mod q718;
336336
mod q720;
337337
mod q721;
338338
mod q724;
339+
mod q725;
339340
mod q728;
340341
mod q733;
341342
mod q738;

‎src/q/q725.rs‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
use crate::q::Solution;
2+
3+
#[derive(PartialEq, Eq, Clone, Debug)]
4+
pub struct ListNode {
5+
pub val: i32,
6+
pub next: Option<Box<ListNode>>,
7+
}
8+
9+
impl ListNode {
10+
#[inline]
11+
fn new(val: i32) -> Self {
12+
ListNode {
13+
next: None,
14+
val,
15+
}
16+
}
17+
}
18+
19+
#[allow(unused)]
20+
impl Solution {
21+
pub fn split_list_to_parts(head: Option<Box<ListNode>>, k: i32) -> Vec<Option<Box<ListNode>>> {
22+
// 方法1
23+
// 将所有的Node都断开,根据Node总数n来判断
24+
// 如果n > k,则直接用 each = n/k 来划分,同时如果不能整除,就通过余数m,在前m个部分多一个Node
25+
// 如果n <= k,则直接每个节点单独存储
26+
// AC 0ms 2mb 43/43
27+
let mut head = head;
28+
let mut node_list = Vec::new();
29+
while let Some(mut node) = head {
30+
head = node.next.take();
31+
node_list.push(Some(node));
32+
}
33+
let n = node_list.len();
34+
let k = k as usize;
35+
if n <= k {
36+
while node_list.len() != k { node_list.push(None); }
37+
return node_list;
38+
}
39+
40+
let part = n / k;
41+
let mut rem = n % k;
42+
let mut ans = Vec::new();
43+
let mut node_idx = 0;
44+
while node_idx < n {
45+
let cnt = if rem > 0 {
46+
rem -= 1;
47+
part + 1
48+
} else { part };
49+
let limit = cnt + node_idx;
50+
51+
let mut head = Some(Box::new(ListNode { val: 0, next: None }));
52+
let mut head_ptr = head.as_mut();
53+
while head_ptr.is_some() && node_idx < limit {
54+
head_ptr.as_mut().unwrap().next = node_list[node_idx].take();
55+
head_ptr = head_ptr.unwrap().next.as_mut();
56+
node_idx += 1;
57+
}
58+
ans.push(head.unwrap().next.take());
59+
}
60+
ans
61+
}
62+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /