文章目录
- 题目描述
- 题解思路
- 题解代码
- 题目链接
题目描述
题解思路
我们只需要遍历长度长度为k的窗口,然后把窗口内数字之和填充到结果数组中的对应位置即可
题解代码
impl Solution {
pub fn decrypt(code: Vec<i32>, k: i32) -> Vec<i32> {
let n = code.len();
let mut ans = vec![0i32; n];
if k == 0 {
return ans;
}
let mut sum = 0;
if k > 0 {
for i in 1..=k as usize {
sum += code[i];
}
ans[0] = sum;
for i in 1..n {
sum += code[(i + k as usize) % n] - code[i];
ans[i] = sum;
}
} else {
for i in k..0 {
sum += code[n + i as usize];
}
ans[0] = sum;
for i in 1..n {
sum += code[i - 1] - code[(i + k as usize - 1 + n) % n];
ans[i] = sum;
}
}
ans
}
}
题目链接
https://leetcode.cn/problems/defuse-the-bomb/