diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 5b9d90aa..8bbedb59 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -240,6 +240,47 @@ class Solution: ``` +### Rust + +```rust + +use std::collections::VecDeque; +impl Solution { + const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)]; + pub fn num_islands(grid: Vec>) -> i32 { + let mut visited = vec![vec![false; grid[0].len()]; grid.len()]; + let mut res = 0; + for (i, chars) in grid.iter().enumerate() { + for (j, &c) in chars.iter().enumerate() { + if !visited[i][j] && c == '1' { + res += 1; + Self::bfs(&grid, &mut visited, (i as i32, j as i32)); + } + } + } + res + } + + pub fn bfs(grid: &Vec>, visited: &mut Vec>, (x, y): (i32, i32)) { + let mut queue = VecDeque::new(); + queue.push_back((x, y)); + visited[x as usize][y as usize] = true; + while let Some((cur_x, cur_y)) = queue.pop_front() { + for (dx, dy) in Self::DIRECTIONS { + let (nx, ny) = (cur_x + dx, cur_y + dy); + if nx < 0 || nx >= grid.len() as i32 || ny < 0 || ny >= grid[0].len() as i32 { + continue; + } + let (nx, ny) = (nx as usize, ny as usize); + if grid[nx][ny] == '1' && !visited[nx][ny] { + visited[nx][ny] = true; + queue.push_back((nx as i32, ny as i32)); + } + } + } + } +} +```

diff --git a/problems/0200.岛屿数量.深搜版.md b/problems/0200.岛屿数量.深搜版.md index f610e323..905c0979 100644 --- a/problems/0200.岛屿数量.深搜版.md +++ b/problems/0200.岛屿数量.深搜版.md @@ -279,6 +279,42 @@ class Solution: return result ``` +Rust: + + +```rust +impl Solution { + const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)]; + pub fn num_islands(grid: Vec>) -> i32 { + let mut visited = vec![vec![false; grid[0].len()]; grid.len()]; + let mut res = 0; + for (i, chars) in grid.iter().enumerate() { + for (j, &c) in chars.iter().enumerate() { + if !visited[i][j] && c == '1' { + res += 1; + Self::dfs(&grid, &mut visited, (i as i32, j as i32)); + } + } + } + res + } + + pub fn dfs(grid: &Vec>, visited: &mut Vec>, (x, y): (i32, i32)) { + for (dx, dy) in Self::DIRECTIONS { + let (nx, ny) = (x + dx, y + dy); + if nx < 0 || nx >= grid.len() as i32 || ny < 0 || ny >= grid[0].len() as i32 { + continue; + } + let (nx, ny) = (nx as usize, ny as usize); + if grid[nx][ny] == '1' && !visited[nx][ny] { + visited[nx][ny] = true; + Self::dfs(grid, visited, (nx as i32, ny as i32)); + } + } + } +} +``` +

diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index fcdeae7b..ab144f43 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -345,6 +345,79 @@ class Solution { } ``` +```java +/* 该方法是对第二个方法的改进,主要变化在于将某点的所有终点变更为链表的形式,优点在于 + 1.添加终点时直接在对应位置添加节点,避免了TreeMap增元素时的频繁调整 + 2.同时每次对终点进行增加删除查找时直接通过下标操作,避免hashMap反复计算hash*/ +class Solution { + //key为起点,value是有序的终点的列表 + Map> ticketMap = new HashMap<>(); + LinkedList result = new LinkedList<>(); + int total; + + public List findItinerary(List> tickets) { + total = tickets.size() + 1; + //遍历tickets,存入ticketMap中 + for (List ticket : tickets) { + addNew(ticket.get(0), ticket.get(1)); + } + deal("JFK"); + return result; + } + + boolean deal(String currentLocation) { + result.add(currentLocation); + //机票全部用完,找到最小字符路径 + if (result.size() == total) { + return true; + } + //当前位置的终点列表 + LinkedList targetLocations = ticketMap.get(currentLocation); + //没有从当前位置出发的机票了,说明这条路走不通 + if (targetLocations != null && !targetLocations.isEmpty()) { + //终点列表中遍历到的终点 + String targetLocation; + //遍历从当前位置出发的机票 + for (int i = 0; i < targetLocations.size(); i++) { + targetLocation = targetLocations.get(i); + //删除终点列表中当前的终点 + targetLocations.remove(i); + //递归 + if (deal(targetLocation)) { + return true; + } + //路线走不通,将机票重新加回去 + targetLocations.add(i, targetLocation); + result.removeLast(); + } + } + return false; + } + + /** + * 在map中按照字典顺序添加新元素 + * + * @param start 起点 + * @param end 终点 + */ + void addNew(String start, String end) { + LinkedList startAllEnd = ticketMap.getOrDefault(start, new LinkedList<>()); + if (!startAllEnd.isEmpty()) { + for (int i = 0; i < startAllEnd.size(); i++) { + if (end.compareTo(startAllEnd.get(i)) < 0) { + startAllEnd.add(i, end); + return; + } + } + startAllEnd.add(startAllEnd.size(), end); + } else { + startAllEnd.add(end); + ticketMap.put(start, startAllEnd); + } + } +} +``` + ### Python 回溯 使用used数组 diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md index f01d8333..45797fb6 100644 --- a/problems/0496.下一个更大元素I.md +++ b/problems/0496.下一个更大元素I.md @@ -396,25 +396,33 @@ function nextGreaterElement(nums1: number[], nums2: number[]): number[] { ### Rust ```rust +use std::collections::HashMap; impl Solution { pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { - let mut ans = vec![-1; nums1.len()]; - use std::collections::HashMap; - let mut map = HashMap::new(); - for (idx, &i) in nums1.iter().enumerate() { - map.insert(i, idx); + let (mut res, mut map) = (vec![-1; nums1.len()], HashMap::new()); + if nums1.is_empty() { + return res; } + + nums1.into_iter().enumerate().for_each(|(v, k)| { + map.insert(k, v); + }); + let mut stack = vec![]; - for (idx, &i) in nums2.iter().enumerate() { - while !stack.is_empty() && nums2[*stack.last().unwrap()] < i { - let pos = stack.pop().unwrap(); - if let Some(&jdx) = map.get(&nums2[pos]) { - ans[jdx] = i; + for (i, &value) in nums2.iter().enumerate() { + while let Some(&top) = stack.last() { + if value <= nums2[top] { + break; + } + let stacked_index = stack.pop().unwrap(); + if let Some(&mapped_index) = map.get(&nums2[stacked_index]) { + res[mapped_index] = value; } } - stack.push(idx); + stack.push(i); } - ans + + res } } ``` diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index 3bddd298..c001df50 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -293,6 +293,28 @@ impl Solution { } ``` +> 版本二: + +```rust +impl Solution { + pub fn next_greater_elements(nums: Vec) -> Vec { + let (mut stack, mut res) = (vec![], vec![-1; nums.len()]); + + for i in 0..nums.len() * 2 { + while let Some(&top) = stack.last() { + if nums[i % nums.len()] <= nums[top] { + break; + } + let saved_index = stack.pop().unwrap(); + res[saved_index] = nums[i % nums.len()]; + } + stack.push(i % nums.len()); + } + + res + } +} +```

diff --git a/problems/0797.所有可能的路径.md b/problems/0797.所有可能的路径.md index ec8288c6..9d14bd7c 100644 --- a/problems/0797.所有可能的路径.md +++ b/problems/0797.所有可能的路径.md @@ -217,7 +217,29 @@ class Solution: self.path.pop() # 回溯 ``` +### Rust +```rust +impl Solution { + pub fn all_paths_source_target(graph: Vec>) -> Vec> { + let (mut res, mut path) = (vec![], vec![0]); + Self::dfs(&graph, &mut path, &mut res, 0); + res + } + + pub fn dfs(graph: &Vec>, path: &mut Vec, res: &mut Vec>, node: usize) { + if node == graph.len() - 1 { + res.push(path.clone()); + return; + } + for &v in &graph[node] { + path.push(v); + Self::dfs(graph, path, res, v as usize); + path.pop(); + } + } +} +```