【问题标题】:How to have the .max() return the i32 datatype?如何让 .max() 返回 i32 数据类型?
【发布时间】:2021-06-20 18:26:37
【问题描述】:

我有以下代码:

impl Solution {
    
    pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
        let mut result = vec![];
        for i in 0..nums.len() as i32 - (k - 1) {
            //println!("{}", nums[i as usize..(i + k) as usize].iter().max());
            result.push(nums[i as usize..(i + k) as usize].iter().max());
        }
        return result;
    }
}

我想从 nums 向量的开头到结尾返回每个 k 大小的窗口的最大值。但是,.iter().max() 表单返回的是 std::option::Option 类型,而不是 i32 类型。我也试过as i32,但这是不允许的。如何解决这个问题?

【问题讨论】:

  • 首先你应该决定当 vec 为空或 k 为负时你想要发生什么。那你应该看看Option的方法。

标签: rust casting


【解决方案1】:

max() 返回一个 Option,因为在空迭代器的情况下没有可返回的合理值。

您需要处理Option 并在这种情况下提供合理的东西。例如0:

pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
    let mut result = vec![];
    for i in 0..nums.len() as i32 - (k - 1) {
        result.push(
            nums[i as usize..(i + k) as usize]
                .iter()
                .max()
                .copied() // because the iterator is over &i32 and you need i32
                .unwrap_or(0),
        );
    }
    return result;
}

n.b.如上面的Denys Séguret commented,您还需要正确处理k 为负数的情况:您的代码将按照编写的方式出现恐慌。

【讨论】:

    猜你喜欢
    • 2010-12-26
    • 2021-04-23
    • 2017-09-13
    • 1970-01-01
    • 2014-12-13
    • 2014-02-14
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多