classSolution: defdecrypt(self, code: List[int], k: int) -> List[int]: if k == 0: return [0] * len(code) res = [] n = len(code) code += code if k > 0: l, r = 1, k else: l, r = n + k, n - 1 w = sum(code[l:r+1]) for i inrange(n): res.append(w) w -= code[l] w += code[r + 1] l, r = l + 1, r + 1 return res
publicclassSolution { publicint[] Decrypt(int[] code, int k) { int n = code.Length; if (k == 0) { returnnewint[n]; } int[] res = newint[n]; int[] newCode = newint[n * 2]; Array.Copy(code, 0, newCode, 0, n); Array.Copy(code, 0, newCode, n, n); code = newCode; int l = k > 0 ? 1 : n + k; int r = k > 0 ? k : n - 1; int w = 0; for (int i = l; i <= r; i++) { w += code[i]; } for (int i = 0; i < n; i++) { res[i] = w; w -= code[l]; w += code[r + 1]; l++; r++; } return res; } }
classSolution { public: vector<int> decrypt(vector<int>& code, int k){ int n = code.size(); vector<int> res(n); if (k == 0) { return res; } code.resize(n * 2); copy(code.begin(), code.begin() + n, code.begin() + n); int l = k > 0 ? 1 : n + k; int r = k > 0 ? k : n - 1; int w = 0; for (int i = l; i <= r; i++) { w += code[i]; } for (int i = 0; i < n; i++) { res[i] = w; w -= code[l]; w += code[r + 1]; l++; r++; } return res; } };
var decrypt = function(code, k) { const n = code.length; if (k === 0) { returnnewArray(n).fill(0); } const res = newArray(n).fill(0); const newCode = newArray(n * 2).fill(0).map((_, idx) => { return code[idx % code.length]; }); code = newCode; let l = k > 0 ? 1 : n + k; let r = k > 0 ? k : n - 1; let w = 0; for (let i = l; i <= r; i++) { w += code[i]; } for (let i = 0; i < n; i++) { res[i] = w; w -= code[l]; w += code[r + 1]; l++; r++; } return res; };
funcdecrypt(code []int, k int) []int { n := len(code) ans := make([]int, n) if k == 0 { return ans } code = append(code, code...) l, r := 1, k if k < 0 { l, r = n+k, n-1 } sum := 0 for _, v := range code[l : r+1] { sum += v } for i := range ans { ans[i] = sum sum -= code[l] sum += code[r+1] l, r = l+1, r+1 } return ans }
复杂度分析
时间复杂度:O(n),其中 n 为数组 code 的长度。
空间复杂度:O(n),其中 n 为数组 code 的长度,主要为数组拼接后的空间开销,也可以通过取模映射操作来将空间复杂度降到 O(1)。