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 a93d922

Browse files
author
ruislan
committed
solved q382
1 parent 4bde2db commit a93d922

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

‎src/q/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ mod q371;
210210
mod q374;
211211
mod q375;
212212
mod q377;
213+
mod q382;
213214
mod q383;
214215
mod q384;
215216
mod q386;

‎src/q/q382.rs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
use std::ops::Range;
2+
3+
use rand::prelude::*;
4+
5+
#[derive(PartialEq, Eq, Clone, Debug)]
6+
pub struct ListNode {
7+
pub val: i32,
8+
pub next: Option<Box<ListNode>>,
9+
}
10+
11+
#[allow(unused)]
12+
impl ListNode {
13+
#[inline]
14+
fn new(val: i32) -> Self {
15+
ListNode {
16+
next: None,
17+
val,
18+
}
19+
}
20+
}
21+
22+
// 方法1
23+
// 根据数组的特性,随机访问是O(1)的时间,所以可以使用此数据结构来缓存节点数据
24+
// AC 8ms 4mbÏ
25+
struct Solution {
26+
cache: Vec<i32>,
27+
}
28+
29+
#[allow(unused)]
30+
impl Solution {
31+
fn new(head: Option<Box<ListNode>>) -> Self {
32+
let mut node = head.as_ref();
33+
let mut cache = Vec::new();
34+
while node.is_some() {
35+
let ptr = node.unwrap();
36+
cache.push(ptr.val);
37+
node = ptr.next.as_ref();
38+
}
39+
Solution { cache }
40+
}
41+
42+
fn get_random(&self) -> i32 {
43+
let mut rng = rand::thread_rng();
44+
self.cache[rng.gen_range(Range { start: 0, end: self.cache.len() })]
45+
}
46+
}

0 commit comments

Comments
(0)

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