๐Ÿ”Žํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ”„๋กœ์„ธ์Šค

๋ฐ•๋ฏผ์šฐยท2023๋…„ 7์›” 12์ผ
0
post-custom-banner

๋ฌธ์ œ: https://school.programmers.co.kr/learn/courses/30/lessons/42587

์นดํ…Œ๊ณ ๋ฆฌ: ํ

์ถœ์ฒ˜: ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ๊ณ ๋“์  Kit, https://school.programmers.co.kr/learn/challenges?tab=algorithm_practice_kit


โœ๏ธ ๋‚ด ํ’€์ด

์ตœ๋Œ€ํ•œ ์„ ์–ธํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๋ฐฉ๋ฒ•์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์งœ๋ ค๊ณ  ๋…ธ๋ ฅํ–ˆ๋‹ค.

  1. ์ฃผ์–ด์ง„ ์šฐ์„ ์ˆœ์œ„๋“ค์˜ ๋ฐฐ์—ด์„ ๊ฐ ์š”์†Œ์˜ index์™€ ๋ฌถ์–ด ์ƒˆ๋กœ์šด ๋ฐฐ์—ด queue์„ ์ƒ์„ฑํ•œ๋‹ค.

    const queue = priorities.map((priority, index) => {
      return { priority, index };
    });
  2. queue์˜ ๋งจ ์•ž ์š”์†Œ์˜ priority๊ฐ€ ๋‚˜๋จธ์ง€ ์š”์†Œ๋“ค๋ณด๋‹ค ๊ฐ™๊ฑฐ๋‚˜ ํฌ๋ฉด queue์—์„œ ๋‚ด๋ณด๋‚ด๊ณ , cnt๋ฅผ 1 ์ฆ๊ฐ€์‹œํ‚จ๋‹ค. ์•„๋‹ˆ๋ผ๋ฉด, queue์˜ ๋งจ ๋’ค๋กœ ์ด๋™์‹œํ‚จ๋‹ค.

  3. ๋‚ด๋ณด๋‚ด๋ ค๋Š” ์š”์†Œ์˜ index๊ฐ€ location๊ณผ ๊ฐ™๋‹ค๋ฉด, cnt๋ฅผ return ํ•˜๊ณ  ์ข…๋ฃŒํ•œ๋‹ค.


๐Ÿ—’๏ธ ๋‚ด ์ฝ”๋“œ

function solution(priorities, location) {
  const queue = priorities.map((priority, index) => {
    return { priority, index };
  });

  let cnt = 1;
  
  while (queue.length) {
    if (queue.every((item) => item.priority <= queue[0].priority)) {
      if (queue[0].index === location) {
        return cnt;
      } else {
        queue.shift();
        cnt++;
      }
    } else {
      queue.push(queue.shift());
    }
  }

  return cnt;
}
profile
๊พธ์ค€ํžˆ, ๊นŠ๊ฒŒ
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€