mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge branch 'master' of github.com:youngyangyang04/leetcode-master
This commit is contained in:
@ -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<Vec<char>>) -> 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<Vec<char>>, visited: &mut Vec<Vec<bool>>, (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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
@ -279,6 +279,42 @@ class Solution:
|
|||||||
return result
|
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<Vec<char>>) -> 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<Vec<char>>, visited: &mut Vec<Vec<bool>>, (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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
@ -345,6 +345,79 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```java
|
||||||
|
/* 该方法是对第二个方法的改进,主要变化在于将某点的所有终点变更为链表的形式,优点在于
|
||||||
|
1.添加终点时直接在对应位置添加节点,避免了TreeMap增元素时的频繁调整
|
||||||
|
2.同时每次对终点进行增加删除查找时直接通过下标操作,避免hashMap反复计算hash*/
|
||||||
|
class Solution {
|
||||||
|
//key为起点,value是有序的终点的列表
|
||||||
|
Map<String, LinkedList<String>> ticketMap = new HashMap<>();
|
||||||
|
LinkedList<String> result = new LinkedList<>();
|
||||||
|
int total;
|
||||||
|
|
||||||
|
public List<String> findItinerary(List<List<String>> tickets) {
|
||||||
|
total = tickets.size() + 1;
|
||||||
|
//遍历tickets,存入ticketMap中
|
||||||
|
for (List<String> 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<String> 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<String> 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
|
### Python
|
||||||
回溯 使用used数组
|
回溯 使用used数组
|
||||||
|
|
||||||
|
@ -396,25 +396,33 @@ function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
|
|||||||
### Rust
|
### Rust
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
|
use std::collections::HashMap;
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
|
pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
|
||||||
let mut ans = vec![-1; nums1.len()];
|
let (mut res, mut map) = (vec![-1; nums1.len()], HashMap::new());
|
||||||
use std::collections::HashMap;
|
if nums1.is_empty() {
|
||||||
let mut map = HashMap::new();
|
return res;
|
||||||
for (idx, &i) in nums1.iter().enumerate() {
|
|
||||||
map.insert(i, idx);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
nums1.into_iter().enumerate().for_each(|(v, k)| {
|
||||||
|
map.insert(k, v);
|
||||||
|
});
|
||||||
|
|
||||||
let mut stack = vec![];
|
let mut stack = vec![];
|
||||||
for (idx, &i) in nums2.iter().enumerate() {
|
for (i, &value) in nums2.iter().enumerate() {
|
||||||
while !stack.is_empty() && nums2[*stack.last().unwrap()] < i {
|
while let Some(&top) = stack.last() {
|
||||||
let pos = stack.pop().unwrap();
|
if value <= nums2[top] {
|
||||||
if let Some(&jdx) = map.get(&nums2[pos]) {
|
break;
|
||||||
ans[jdx] = i;
|
}
|
||||||
|
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -293,6 +293,28 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 版本二:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn next_greater_elements(nums: Vec<i32>) -> Vec<i32> {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
@ -217,7 +217,29 @@ class Solution:
|
|||||||
self.path.pop() # 回溯
|
self.path.pop() # 回溯
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Rust
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn all_paths_source_target(graph: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
|
||||||
|
let (mut res, mut path) = (vec![], vec![0]);
|
||||||
|
Self::dfs(&graph, &mut path, &mut res, 0);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dfs(graph: &Vec<Vec<i32>>, path: &mut Vec<i32>, res: &mut Vec<Vec<i32>>, 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user