gpt4 book ai didi

multidimensional-array - 为什么这没有通过借阅检查器?

转载 作者:行者123 更新时间:2023-12-03 11:36:17 25 4
gpt4 key购买 nike

我试图通过逐行拆分顶部和底部行来解决leetcode上的螺旋顺序问题,但我遇到了我无法理解的借位检查器问题。这是产生编译错误的最小示例:

pub fn f(mut matrix: &mut [Vec<i32>]) {
while let Some((_, remainder)) = matrix.split_first_mut() {
matrix = remainder;
if let Some((_, remainder)) = matrix.split_first_mut() {
matrix = remainder;
}
}
}
这是我的完整代码,用于说明我要完成的工作:
impl Solution {
pub fn spiral_order(mut matrix: Vec<Vec<i32>>) -> Vec<i32> {
let mut matrix = &mut matrix[..];
if matrix.is_empty() {
return Vec::new();
}
let mut ans = Vec::with_capacity(matrix.len() * matrix[0].len());
while let Some((head, tail)) = matrix.split_first_mut() {
ans.append(head);
matrix = tail;
for row in matrix.iter_mut() {
ans.push(row.pop().unwrap());
}
if let Some((head, tail)) = matrix.split_last_mut() {
matrix = tail;
ans.extend(head.into_iter().rev().map(|&mut x| x));
}
}
ans
}
}
似乎认为内部借用与循环的下一次迭代中的后续外部借用发生冲突,但是我认为应该没问题,因为我将其余部分移回了矩阵,因此在迭代结束之前在其中有一个有效的 &mut [Vec<i32>] 。为什么无法编译,应如何解决?

最佳答案

我无法解释为什么您的原始版本无法编译,但是我不认为split_first_mutsplit_last_mut是完成此任务的工具。我是要简化实现,并改为切换到removepop来使其编译:

fn spiral_order(mut matrix: Vec<Vec<i32>>) -> Vec<i32> {
if matrix.is_empty() {
return Vec::new();
}
let mut ans = Vec::with_capacity(matrix.len() * matrix[0].len());
while !matrix.is_empty() {
let mut head = matrix.remove(0);
ans.append(&mut head);
for row in matrix.iter_mut() {
ans.push(row.pop().unwrap());
}
if let Some(head) = matrix.pop() {
ans.extend(head.into_iter().rev());
}
}
ans
}
playground

最佳解决方案,没有任何 matrix突变或副本:
fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
if matrix.len() == 0 || matrix[0].len() == 0 {
return Vec::new();
}

let mut row = 0;
let mut col = 0;
let mut up = 0;
let mut down = matrix.len() as i32 - 1;
let mut left = 0;
let mut right = matrix[0].len() as i32 - 1;
let mut dir = (0, 1);
let mut ans = Vec::with_capacity(matrix.len() * matrix[0].len());

for _ in 0..(matrix.len() * matrix[0].len()) {
ans.push(matrix[row as usize][col as usize]);

match dir {
(0, 1) if col == right => {
dir = (1, 0);
up += 1;
}
(1, 0) if row == down => {
dir = (0, -1);
right -= 1;
}
(0, -1) if col == left => {
dir = (-1, 0);
down -= 1;
}
(-1, 0) if row == up => {
dir = (0, 1);
left += 1;
}
_ => (),
}

row += dir.0;
col += dir.1;
}

ans
}
playground

关于multidimensional-array - 为什么这没有通过借阅检查器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65854559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com