From b193edc5a8f8489352dfe61fcb8d73ba1c29dd54 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Sat, 23 Jul 2022 20:55:18 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200332.=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=AE=89=E6=8E=92=E8=A1=8C=E7=A8=8B=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0332.重新安排行程 Rust版本 --- problems/0332.重新安排行程.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 71942c79..8b5f797d 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -742,5 +742,33 @@ func (p ticketSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } ``` +### Rust +** 文中的Hashmap嵌套Hashmap的方法因为Rust的所有权问题暂时无法实现,此方法为删除哈希表中元素法 ** +```Rust +use std::collections::HashMap; +impl Solution { + fn backtracking(airport: String, targets: &mut HashMap<&String, Vec<&String>>, result: &mut Vec) { + while let Some(next_airport) = targets.get_mut(&airport).unwrap_or(&mut vec![]).pop() { + Self::backtracking(next_airport.clone(), targets, result); + } + result.push(airport.clone()); + } + + pub fn find_itinerary(tickets: Vec>) -> Vec { + let mut targets: HashMap<&String, Vec<&String>> = HashMap::new(); + let mut result = Vec::new(); + for t in 0..tickets.len() { + targets.entry(&tickets[t][0]).or_default().push(&tickets[t][1]); + } + for (_, target) in targets.iter_mut() { + target.sort_by(|a, b| b.cmp(a)); + } + Self::backtracking("JFK".to_string(), &mut targets, &mut result); + result.reverse(); + result + } +} +``` + -----------------------