1652.拆炸弹
链接:1652.拆炸弹
难度:Easy
标签:数组、滑动窗口
简介:给你 循环 数组 code 和整数密钥 k ,请你返回解密后的结果来拆除炸弹!。
题解 1 - cpp
- 编辑时间:2022-09-24
- 内存消耗:8.2MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
vector<int> decrypt(vector<int>& code, int k) {
int n = code.size();
vector<int> ans(n, 0);
for (int i = 0; i < n; i++) {
if (k > 0) {
for (int j = (i + 1) % n, cnt = 0; cnt < k; cnt++, j = (j + 1) % n) ans[i] += code[j];
} else if (k < 0) {
for (int j = (i - 1 + n) % n, cnt = 0; cnt < -k; cnt++, j = (j - 1 + n) % n) ans[i] += code[j];
}
}
return ans;
}
};
题解 2 - python
- 编辑时间:2024-05-05
- 执行用时:53ms
- 内存消耗:16.42MB
- 编程语言:python
- 解法介绍:遍历。
class Solution:
def decrypt(self, code: List[int], k: int) -> List[int]:
n = len(code)
if k == 0: return [0] * n
def get(idx: int) -> int:
res = 0
next = idx
for _ in range(abs(k)):
next = ((1 if k > 0 else -1) + next + n) % n
res += code[next]
return res
return [get(i) for i in range(n)]
题解 3 - python
- 编辑时间:2024-05-05
- 执行用时:53ms
- 内存消耗:16.42MB
- 编程语言:python
- 解法介绍:遍历。
class Solution:
def decrypt(self, code: List[int], k: int) -> List[int]:
n = len(code)
if k == 0: return [0] * n
def get(idx: int) -> int:
res = 0
next = idx
for _ in range(abs(k)):
next = ((1 if k > 0 else -1) + next + n) % n
res += code[next]
return res
return [get(i) for i in range(n)]