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 d0f7d46

Browse files
Merge branch 'master' of github.com:youngyangyang04/leetcode-master
2 parents 7e7e0cd + ab90e74 commit d0f7d46

6 files changed

+214
-12
lines changed

‎problems/0200.岛屿数量.广搜版.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,47 @@ class Solution:
240240

241241
```
242242

243+
### Rust
244+
245+
```rust
246+
247+
use std::collections::VecDeque;
248+
impl Solution {
249+
const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)];
250+
pub fn num_islands(grid: Vec<Vec<char>>) -> i32 {
251+
let mut visited = vec![vec![false; grid[0].len()]; grid.len()];
252+
let mut res = 0;
253+
for (i, chars) in grid.iter().enumerate() {
254+
for (j, &c) in chars.iter().enumerate() {
255+
if !visited[i][j] && c == '1' {
256+
res += 1;
257+
Self::bfs(&grid, &mut visited, (i as i32, j as i32));
258+
}
259+
}
260+
}
261+
res
262+
}
263+
264+
pub fn bfs(grid: &Vec<Vec<char>>, visited: &mut Vec<Vec<bool>>, (x, y): (i32, i32)) {
265+
let mut queue = VecDeque::new();
266+
queue.push_back((x, y));
267+
visited[x as usize][y as usize] = true;
268+
while let Some((cur_x, cur_y)) = queue.pop_front() {
269+
for (dx, dy) in Self::DIRECTIONS {
270+
let (nx, ny) = (cur_x + dx, cur_y + dy);
271+
if nx < 0 || nx >= grid.len() as i32 || ny < 0 || ny >= grid[0].len() as i32 {
272+
continue;
273+
}
274+
let (nx, ny) = (nx as usize, ny as usize);
275+
if grid[nx][ny] == '1' && !visited[nx][ny] {
276+
visited[nx][ny] = true;
277+
queue.push_back((nx as i32, ny as i32));
278+
}
279+
}
280+
}
281+
}
282+
}
283+
```
243284
<p align="center">
244285
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
245286
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

‎problems/0200.岛屿数量.深搜版.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,42 @@ class Solution:
279279
return result
280280
```
281281

282+
Rust:
283+
284+
285+
```rust
286+
impl Solution {
287+
const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)];
288+
pub fn num_islands(grid: Vec<Vec<char>>) -> i32 {
289+
let mut visited = vec![vec![false; grid[0].len()]; grid.len()];
290+
let mut res = 0;
291+
for (i, chars) in grid.iter().enumerate() {
292+
for (j, &c) in chars.iter().enumerate() {
293+
if !visited[i][j] && c == '1' {
294+
res += 1;
295+
Self::dfs(&grid, &mut visited, (i as i32, j as i32));
296+
}
297+
}
298+
}
299+
res
300+
}
301+
302+
pub fn dfs(grid: &Vec<Vec<char>>, visited: &mut Vec<Vec<bool>>, (x, y): (i32, i32)) {
303+
for (dx, dy) in Self::DIRECTIONS {
304+
let (nx, ny) = (x + dx, y + dy);
305+
if nx < 0 || nx >= grid.len() as i32 || ny < 0 || ny >= grid[0].len() as i32 {
306+
continue;
307+
}
308+
let (nx, ny) = (nx as usize, ny as usize);
309+
if grid[nx][ny] == '1' && !visited[nx][ny] {
310+
visited[nx][ny] = true;
311+
Self::dfs(grid, visited, (nx as i32, ny as i32));
312+
}
313+
}
314+
}
315+
}
316+
```
317+
282318
<p align="center">
283319
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
284320
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

‎problems/0332.重新安排行程.md‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,79 @@ class Solution {
345345
}
346346
```
347347

348+
```java
349+
/* 该方法是对第二个方法的改进,主要变化在于将某点的所有终点变更为链表的形式,优点在于
350+
1.添加终点时直接在对应位置添加节点,避免了TreeMap增元素时的频繁调整
351+
2.同时每次对终点进行增加删除查找时直接通过下标操作,避免hashMap反复计算hash*/
352+
class Solution {
353+
//key为起点,value是有序的终点的列表
354+
Map<String, LinkedList<String>> ticketMap = new HashMap<>();
355+
LinkedList<String> result = new LinkedList<>();
356+
int total;
357+
358+
public List<String> findItinerary(List<List<String>> tickets) {
359+
total = tickets.size() + 1;
360+
//遍历tickets,存入ticketMap中
361+
for (List<String> ticket : tickets) {
362+
addNew(ticket.get(0), ticket.get(1));
363+
}
364+
deal("JFK");
365+
return result;
366+
}
367+
368+
boolean deal(String currentLocation) {
369+
result.add(currentLocation);
370+
//机票全部用完,找到最小字符路径
371+
if (result.size() == total) {
372+
return true;
373+
}
374+
//当前位置的终点列表
375+
LinkedList<String> targetLocations = ticketMap.get(currentLocation);
376+
//没有从当前位置出发的机票了,说明这条路走不通
377+
if (targetLocations != null && !targetLocations.isEmpty()) {
378+
//终点列表中遍历到的终点
379+
String targetLocation;
380+
//遍历从当前位置出发的机票
381+
for (int i = 0; i < targetLocations.size(); i++) {
382+
targetLocation = targetLocations.get(i);
383+
//删除终点列表中当前的终点
384+
targetLocations.remove(i);
385+
//递归
386+
if (deal(targetLocation)) {
387+
return true;
388+
}
389+
//路线走不通,将机票重新加回去
390+
targetLocations.add(i, targetLocation);
391+
result.removeLast();
392+
}
393+
}
394+
return false;
395+
}
396+
397+
/**
398+
* 在map中按照字典顺序添加新元素
399+
*
400+
* @param start 起点
401+
* @param end 终点
402+
*/
403+
void addNew(String start, String end) {
404+
LinkedList<String> startAllEnd = ticketMap.getOrDefault(start, new LinkedList<>());
405+
if (!startAllEnd.isEmpty()) {
406+
for (int i = 0; i < startAllEnd.size(); i++) {
407+
if (end.compareTo(startAllEnd.get(i)) < 0) {
408+
startAllEnd.add(i, end);
409+
return;
410+
}
411+
}
412+
startAllEnd.add(startAllEnd.size(), end);
413+
} else {
414+
startAllEnd.add(end);
415+
ticketMap.put(start, startAllEnd);
416+
}
417+
}
418+
}
419+
```
420+
348421
### Python
349422
回溯 使用used数组
350423

‎problems/0496.下一个更大元素I.md‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -396,25 +396,33 @@ function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
396396
### Rust
397397

398398
```rust
399+
use std::collections::HashMap;
399400
impl Solution {
400401
pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
401-
let mut ans = vec![-1; nums1.len()];
402-
use std::collections::HashMap;
403-
let mut map = HashMap::new();
404-
for (idx, &i) in nums1.iter().enumerate() {
405-
map.insert(i, idx);
402+
let (mut res, mut map) = (vec![-1; nums1.len()], HashMap::new());
403+
if nums1.is_empty() {
404+
return res;
406405
}
406+
407+
nums1.into_iter().enumerate().for_each(|(v, k)| {
408+
map.insert(k, v);
409+
});
410+
407411
let mut stack = vec![];
408-
for (idx, &i) in nums2.iter().enumerate() {
409-
while !stack.is_empty() && nums2[*stack.last().unwrap()] < i {
410-
let pos = stack.pop().unwrap();
411-
if let Some(&jdx) = map.get(&nums2[pos]) {
412-
ans[jdx] = i;
412+
for (i, &value) in nums2.iter().enumerate() {
413+
while let Some(&top) = stack.last() {
414+
if value <= nums2[top] {
415+
break;
416+
}
417+
let stacked_index = stack.pop().unwrap();
418+
if let Some(&mapped_index) = map.get(&nums2[stacked_index]) {
419+
res[mapped_index] = value;
413420
}
414421
}
415-
stack.push(idx);
422+
stack.push(i);
416423
}
417-
ans
424+
425+
res
418426
}
419427
}
420428
```

‎problems/0503.下一个更大元素II.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,28 @@ impl Solution {
293293
}
294294
```
295295

296+
> 版本二:
297+
298+
```rust
299+
impl Solution {
300+
pub fn next_greater_elements(nums: Vec<i32>) -> Vec<i32> {
301+
let (mut stack, mut res) = (vec![], vec![-1; nums.len()]);
302+
303+
for i in 0..nums.len() * 2 {
304+
while let Some(&top) = stack.last() {
305+
if nums[i % nums.len()] <= nums[top] {
306+
break;
307+
}
308+
let saved_index = stack.pop().unwrap();
309+
res[saved_index] = nums[i % nums.len()];
310+
}
311+
stack.push(i % nums.len());
312+
}
313+
314+
res
315+
}
316+
}
317+
```
296318

297319
<p align="center">
298320
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

‎problems/0797.所有可能的路径.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,29 @@ class Solution:
217217
self.path.pop() # 回溯
218218
```
219219

220+
### Rust
221+
222+
```rust
223+
impl Solution {
224+
pub fn all_paths_source_target(graph: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
225+
let (mut res, mut path) = (vec![], vec![0]);
226+
Self::dfs(&graph, &mut path, &mut res, 0);
227+
res
228+
}
220229

230+
pub fn dfs(graph: &Vec<Vec<i32>>, path: &mut Vec<i32>, res: &mut Vec<Vec<i32>>, node: usize) {
231+
if node == graph.len() - 1 {
232+
res.push(path.clone());
233+
return;
234+
}
235+
for &v in &graph[node] {
236+
path.push(v);
237+
Self::dfs(graph, path, res, v as usize);
238+
path.pop();
239+
}
240+
}
241+
}
242+
```
221243

222244
<p align="center">
223245
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
(0)

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