在 Rust 中解决 leetcode 上的 shuffle 数组问题

时间:2021-01-10 22:52:49

标签: rust

fn shuffle(nums: Vec<i32>, n: i32) -> Vec<i32> {
    let mut res: Vec<i32>;
    let mut i = 0;

    while i < n {
        res.push(nums[i]);
        res.push(nums[n + i]);
        i += 1;
    }

    res
}

当我尝试索引 nums 数组以获取 [i] 处的值时,出现此错误:

the type [i32] cannot be indexed by i32
the trait SliceIndex<[i32]> is not implemented for i32
required because of the requirements on the impl of Index<i32> for Vec<i32>

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您只能使用 Vec 索引 usize,因此您必须将 i32 转换为 usize 才能索引到 nums

fn shuffle(nums: Vec<i32>, n: i32) -> Vec<i32> {
    let mut res = Vec::new();
    let mut i = 0;

    while i < n {
        res.push(nums[i as usize]);
        res.push(nums[(n + i) as usize]);
        i += 1;
    }

    res
}

playground