2024每日刷题(127)
Leetcode—1652. 拆炸弹
实现代码
class Solution {
public:vector<int> decrypt(vector<int>& code, int k) {int codeSize = code.size();vector<int> ans(codeSize, 0);if(k == 0) {return ans;}if(k > 0) {for(int i = 0; i < codeSize; i++) {for(int j = 1; j <= k; j++) {ans[i] += code[(i + j) % codeSize];}}} else {for(int i = 0; i < codeSize; i++) {for(int j = -1; j >= k; j--) {ans[i] += code[(i + j + codeSize) % codeSize];}}}return ans;}
};
运行结果
滑动窗口实现代码
class Solution {
public:vector<int> decrypt(vector<int>& code, int k) {int n = code.size();vector<int> ans(n);if(k == 0) {return ans;}int sum = 0;int start = k > 0 ? 1: n + k;int end = k > 0 ? k: n - 1;for(int i = start; i <= end; i++) {sum += code[i];}for(int i = 0; i < n; i++) {ans[i] = sum;sum -= code[start++ % n];sum += code[++end % n];}return ans;}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!