๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 560 - Subarray Sum Equals K (Medium)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 560๋ฒˆ

ํ’€์ด ๊ณผ์ •

ํŠน์ • ๊ตฌ๊ฐ„์˜ ํ•ฉ์ด k ์ด ๋˜๋Š” ์ด ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์›๋ž˜ ํˆฌ ํฌ์ธํ„ฐ ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ตฌํ•˜๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ ์Œ์ˆ˜๊ฐ€ ์กด์žฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์˜ฌ๋ฐ”๋ฅธ ๊ฐ’์„ ๊ตฌํ•  ์ˆ˜ ์—†์—ˆ์Šต๋‹ˆ๋‹ค.
๋”ฐ๋ผ์„œ 1์ฐจ์› ๋ฐฐ์—ด์— ๋ˆ„์  ํ•ฉ์„ ๊ณ„์† ๊ธฐ๋กํ•˜๋ฉด์„œ ๊ณ„์‚ฐ์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.
์—ฌ๊ธฐ์„œ ํ•ฉ์ด k ๊ฐ€ ๋˜๋Š” ๊ตฌ๊ฐ„์„ ์ฐพ๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ƒ๊ฐํ•ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

a, b, ... e, f ...

๋งŒ์•ฝ f ๊นŒ์ง€์˜ ํ•ฉ์ด 30์ด๊ณ  ์šฐ๋ฆฌ๊ฐ€ ์ฐพ๋Š” k = 20 ์ผ ๋•Œ a ~ f ๊นŒ์ง€ ์ˆซ์ž ์ค‘์—์„œ ํ•ฉ์ด 10 ์ธ ์ง€์ ์„ ์ฐพ์œผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
๊ทธ ์ด์œ ๋Š” a ~ b = 10 ์ด๋ผ๋ฉด c ~ f ์˜ ๊ตฌ๊ฐ„์ด 30 - 10 = 20 ์ด ๋˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. (๊ตฌ๊ฐ„ ํ•ฉ ์•Œ๊ณ ๋ฆฌ์ฆ˜)

์ฝ”๋“œ

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraySum = function (nums, k) {
  let answer = 0,
    acc = 0;
  const prefix = new Map();
  prefix.set(0, 1);

  for (const num of nums) {
    acc += num;
    if (prefix.has(acc - k)) {
      answer += prefix.get(acc - k);
    }

    if (prefix.has(acc)) {
      prefix.set(acc, prefix.get(acc) + 1);
    } else {
      prefix.set(acc, 1);
    }
  }

  return answer;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 75 - Sort Colors (Medium)  (0) 2021.03.04
LeetCode 416 - Partition Equal Subset Sum (Medium)  (0) 2021.03.04
LeetCode 752 - Open the Lock (Medium)  (0) 2021.03.04
LeetCode 11 - Container With Most Water (Medium)  (0) 2021.03.04
LeetCode 763 - Partition Labels (Medium)  (0) 2021.03.04

๐Ÿ’ฌ ๋Œ“๊ธ€