Skip to content

Latest commit

 

History

History
48 lines (42 loc) · 1.06 KB

1652.拆炸弹.md

File metadata and controls

48 lines (42 loc) · 1.06 KB

1652.拆炸弹

/*
 * @lc app=leetcode.cn id=1652 lang=typescript
 *
 * [1652] 拆炸弹
 */

// @lc code=start
function decrypt(code: number[], k: number): number[] {}
// @lc code=end

解法 1: 模拟

function decrypt(code: number[], k: number): number[] {
  const n = code.length
  const res: number[] = new Array(n)
  for (let i = 0; i < n; i++) {
    if (k > 0) {
      let ans = 0
      for (let j = (i + 1) % n, _ = 0; _ < k; _++, j = (j + 1) % n) ans += code[j]
      res[i] = ans
    } else if (k < 0) {
      let ans = 0
      for (let j = (i - 1 + n) % n, _ = 0; _ < -k; _++, j = (j - 1 + n) % n) ans += code[j]
      res[i] = ans
    } else {
      res[i] = 0
    }
  }
  return res
}

Case

test.each([
  { input: { code: [5, 7, 1, 4], k: 3 }, output: [12, 10, 16, 13] },
  { input: { code: [1, 2, 3, 4], k: 0 }, output: [0, 0, 0, 0] },
  { input: { code: [2, 4, 9, 3], k: -2 }, output: [12, 5, 6, 13] },
])('input: code = $input.code, k = $input.k', ({ input: { code, k }, output }) => {
  expect(decrypt(code, k)).toEqual(output)
})