๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section05 - 3 - ์—ฐ์† ๋ถ€๋ถ„์ˆ˜์—ด1

by YWTechIT 2021. 8. 25.
728x90

๐Ÿ“ section05 - 3 - ์—ฐ์† ๋ถ€๋ถ„์ˆ˜์—ด1

N๊ฐœ์˜ ์ˆ˜๊ฐ€ ์žˆ์„ ๋•Œ, ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ์ด target๊ณผ ๋™์ผํ•œ ๊ฒฝ์šฐ๊ฐ€ ๋ช‡ ๋ฒˆ์žˆ๋Š”์ง€ ์ฐพ๋Š” ๋ฌธ์ œ๋‹ค. ์ด์ „๊นŒ์ง€๋Š” ์ด์™€ ๋น„์Šทํ•œ ์œ ํ˜•์˜ ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณธ ๊ฒฝํ—˜์ด ์—†๊ธฐ ๋•Œ๋ฌธ์— ์–ด๋ ค์› ๋‹ค. N<=100,000 ์ผ ๋•Œ ์ตœ๋Œ€ O(nlogn)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๋งŒ์กฑํ•ด์•ผ ์‹œ๊ฐ„ ์ดˆ๊ณผ๋ฅผ ๋ฐ›์ง€ ์•Š๋Š”๋‹ค. ์ฆ‰, bruteForce(O(N^2)) ๋Œ€์‹  ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

 

์ฝ”๋“œ์—์„œ๋Š” while + while๋ฌธ์„ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ, ๋ฐ˜๋ณต๋ฌธ์„ 2๊ฐœ ์‚ฌ์šฉํ•˜๋ฉด ๋ฌด์กฐ๊ฑด O(N^2))์ด ๋˜๋Š” ๊ฒŒ ์•„๋‹Œ๊ฐ€์š”?๋ผ๊ณ  ํ•  ์ˆ˜๋„ ์žˆ๋‹ค. ๊ฒฐ๋ก ์ ์œผ๋กœ๋Š” ๊ทธ๋ ‡์ง€ ์•Š๋‹ค. ์ด์ค‘ ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•˜๋”๋ผ๋„ ๊ทธ ์•ˆ์—์„œ ์–ด๋–ค ์—ฐ์‚ฐ์„ ํ–ˆ๋Š๋ƒ์— ๋”ฐ๋ผ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ๋Š”๋ฐ, ํ˜„์žฌ ์ฝ”๋“œ์—์„œ๋Š” ์•ˆ์ชฝ ๋ฃจํ”„๊ฐ€ ๋„๋Š” ์ดํšŸ์ˆ˜๋ฅผ ๋‹ค ํ•ฉํ–ˆ์„ ๋•Œ ๊ผญ O(N)์ด ๋˜์ง€ ์•Š๋Š”๋‹ค. ์™œ๋ƒํ•˜๋ฉด ์•ˆ์ชฝ ๋ฃจํ”„์˜ ์กฐ๊ฑด์„ ๋ณด๋ฉด sum>=m ์ธ๋ฐ, ๋งŒ์•ฝ, ํ˜„์žฌ ์กฐ๊ฑด์ด sum<m์ด๋ผ๋ฉด ์•ˆ์ชฝ ๋ฃจํ”„๋Š” ์‹คํ–‰๋˜์ง€ ์•Š์„ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

  1. ํˆฌ ํฌ์ธํ„ฐ ๋ณ€์ˆ˜์ธ lt=rt=0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
  2. sum ๋ณ€์ˆ˜์— arr[rt] ๊ฐ’์„ ๋”ํ•œ๋‹ค.
  3. sum === target ์ด๋ฉด, cnt++ํ•ด์ค€๋‹ค.
  4. ๋งŒ์•ฝ, sum>target์ด๋ฉด, lt๋ฅผ ์ฆ๊ฐ€ํ•ด์„œ sum<=target์ด ๋  ๋•Œ๊นŒ์ง€ ๋นผ์ค˜์•ผ ํ•œ๋‹ค.
  5. while๋ฌธ ์•ˆ์—์„œ lt๋ฅผ ๋นผ์คฌ์„ ๋•Œ๋„ 3๋ฒˆ ๊ณผ์ •์„ ๊ฑฐ์นœ๋‹ค. (์—ฌ๊ธฐ์„œ ์•Œ์•„๋‘์–ด์•ผ ํ•˜๋Š” ์ ์€ sum===target์ด์–ด๋„ lt๋ฅผ ๋นผ์ค˜์•ผ ๋‹ค์Œ rt๋ฅผ ์ฆ๊ฐ€์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.)
728x90
// ๋‚˜์˜ ์ฝ”๋“œ
let n = 8;
let target = 6;
let arr = [1, 2, 1, 3, 1, 1, 1, 2];

console.log(solution(n, target, arr));

function solution(n, target, arr) {
  let lt = (rt = cnt = sum = 0);

  while (rt < n) {
    sum += arr[rt++];
    if (sum === m) cnt++;
    while (sum >= m) {
      sum -= arr[lt++];
      if (sum === m) cnt++;
    }
  }

  return cnt;
}

 

// ๊ฐ•์˜ ์ฝ”๋“œ
let n = 8;
let target = 6;
let arr = [1, 2, 1, 3, 1, 1, 1, 2];

console.log(solution(n, target, arr));

function solution(n, target, arr) {
  let lt = (cnt = sum = 0);

  for (let rt = 0; rt < n; rt++) {
    sum += arr[rt];
    if (sum === target) cnt++;
    while (sum >= target) {
      sum -= arr[lt++];
      if (sum === target) cnt++;
    }
  }
  return cnt;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€