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

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section05 - 2 - ๊ณตํ†ต ์›์†Œ ๊ตฌํ•˜๊ธฐ

by YWTechIT 2021. 8. 24.
728x90

๐Ÿ“ section05 - 2 - ๊ณตํ†ต ์›์†Œ ๊ตฌํ•˜๊ธฐ

A, B ๋‘ ๊ฐœ์˜ ์ง‘ํ•ฉ์ด ์ฃผ์–ด์งˆ ๋•Œ ๊ณตํ†ต ์›์†Œ๋ฅผ ์ถ”์ถœํ•˜์—ฌ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š” ์ด์œ ๋Š” N์˜ ํฌ๊ธฐ๊ฐ€ 30,000์ธ๋ฐ, ์ด๋ฅผ O(N^2)์œผ๋กœ ํ’€๊ฒŒ ๋˜๋ฉด ์ตœ์•…์˜ ๊ฒฝ์šฐ 1์ดˆ๋‹น 9์–ต๋ฒˆ์˜ ์—ฐ์‚ฐ์„ ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚œ๋‹ค. ๋”ฐ๋ผ์„œ, O(N^2) ๋ณด๋‹ค ์ž‘์€ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ๊ณ„์‚ฐํ•ด์•ผ ํ•œ๋‹ค. ๋งŒ์•ฝ, N์˜ ๋ฒ”์œ„๊ฐ€ 30,000๋ณด๋‹ค ๋” ์ž‘๋‹ค๋ฉด O(N^2)์œผ๋กœ bruteForce๋กœ๋„ ํ’€ ์ˆ˜ ์žˆ๋‹ค.bruteForce์˜ ์žฅ์ ์€ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ฒ€์‚ฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ •ํ™•ํ•œ ๊ฒฐ๊ด๊ฐ’์ด ๋‚˜์˜จ๋‹ค๋Š” ์ ์ด๋‹ค.

 

//O(N^2), bruteForce
let n = 5;
let arr1 = [1, 3, 9, 5, 2];

let m = 5;
let arr2 = [3, 2, 5, 7, 8];

console.log(solution(n, arr1, m, arr2));

function solution(n, arr1, m, arr2) {
  let ans = [];

  for (let i = 0; i < n; i++) {
    let target = arr1[i];
    for (let j = 0; j < m; j++) {
      if (target === arr2[j]) ans.push(target);
    }
  }

  ans.sort((a, b) => a - b);
  return ans;
}

 

728x90

 

ํ•˜์ง€๋งŒ, ์ด๋ฒˆ ์„น์…˜์ด ํšจ์œจ์„ฑ์„ ๊ณ ๋ คํ•˜๋Š” ๋ฌธ์ œ์ธ ๋งŒํผ ํˆฌ ํฌ์ธํ„ฐ๋กœ ํ’€์–ด๋ณด์ž. ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด NlogN+N+M ์ฆ‰, O(NlogN)์— ํ’€ ์ˆ˜ ์žˆ๋Š”๋ฐ, ์‹œ๊ฐ„ ๋‚ด์— ๋“ค์–ด์˜ฌ ์ˆ˜ ์žˆ๋‹ค. ํ’€์ด ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

 

  1. ๋‘ ๋ฐฐ์—ด์„ ๊ฐ๊ฐ sort(nlogn)ํ•œ๋‹ค.
  2. ํˆฌ ํฌ์ธํ„ฐ ์ธ๋ฑ์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” p1, p2๋ฅผ 0์œผ๋กœ ์„ ์–ธํ•œ๋‹ค.
  3. ๋งŒ์•ฝ, p2๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ฐ’์ด p1๋ณด๋‹ค ํฌ๋ฉด ํ˜„์žฌ p2 ๋’ค๋กœ๋Š” p1๋ณด๋‹ค ๊ฐ™๊ฑฐ๋‚˜ ์ž‘์€ ๊ฐ’์ด ์—†๋‹ค. ์™œ๋ƒํ•˜๋ฉด ๋ฐฐ์—ด์€ ์ด๋ฏธ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์–ด์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋”ฐ๋ผ์„œ p1++์„ ํ•ด์ค€๋‹ค.
  4. p1===p2์ด๋ฉด ans์— ๋„ฃ๊ณ  ๋‹ค์Œ ์ˆซ์ž๋ฅผ ๊ฒ€์‚ฌํ•˜๊ธฐ ์œ„ํ•ด p1++, p2++ ํ•ด์ค€๋‹ค.
  5. p1>p2์ธ ์ƒํ™ฉ์ด๋ฉด p2++๋ฅผ ํ•ด์ค€๋‹ค.
  6. p1 ํ˜น์€ p2๊ฐ€ n๋ณด๋‹ค ์ปค์ง€๋ฉด ๋ฐ˜๋ณต๋ฌธ์„ ์ข…๋ฃŒํ•œ๋‹ค.(ํ•œ์ชฝ ํƒ์ƒ‰์ด ๋จผ์ € ๋๋‚˜๋ฉด ๋‹ค๋ฅธ ์ชฝ์€ ํƒ์ƒ‰ํ•  ํ•„์š”๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.)

 

// O(NlogN + N + M), Two Pointer
let n = 5;
let arr1 = [1, 3, 9, 5, 2];

let m = 5;
let arr2 = [3, 2, 5, 7, 8];

console.log(solution(n, arr1, m, arr2));

function solution(n, arr1, m, arr2) {
  let ans = [];
  let p1 = (p2 = 0);
  arr1.sort((a, b) => a - b);
  arr2.sort((a, b) => a - b);

  while (p1 < n && p2 < m) {
    if (arr1[p1] === arr2[p2]) {
      ans.push(arr1[p1++]);
      p2++;
    } else if (arr1[p1] < arr2[p2]) p1++;
    else p2++;
  }

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

๋Œ“๊ธ€