Jieunny์˜ ๋ธ”๋กœ๊ทธ

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋‹ฌ๋ฆฌ๊ธฐ ๊ฒฝ์ฃผ ๋ณธ๋ฌธ

Study/Coding Test

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋‹ฌ๋ฆฌ๊ธฐ ๊ฒฝ์ฃผ

Jieunny 2023. 7. 17. 17:05

๐Ÿ“Œ  ๋ฌธ์ œ

์–€์—์„œ๋Š” ๋งค๋…„ ๋‹ฌ๋ฆฌ๊ธฐ ๊ฒฝ์ฃผ๊ฐ€ ์—ด๋ฆฝ๋‹ˆ๋‹ค. ํ•ด์„ค์ง„๋“ค์€ ์„ ์ˆ˜๋“ค์ด ์ž๊ธฐ ๋ฐ”๋กœ ์•ž์˜ ์„ ์ˆ˜๋ฅผ ์ถ”์›”ํ•  ๋•Œ ์ถ”์›”ํ•œ ์„ ์ˆ˜์˜ ์ด๋ฆ„์„ ๋ถ€๋ฆ…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด 1๋“ฑ๋ถ€ํ„ฐ 3๋“ฑ๊นŒ์ง€ "mumu", "soe", "poe" ์„ ์ˆ˜๋“ค์ด ์ˆœ์„œ๋Œ€๋กœ ๋‹ฌ๋ฆฌ๊ณ  ์žˆ์„ ๋•Œ, ํ•ด์„ค์ง„์ด "soe"์„ ์ˆ˜๋ฅผ ๋ถˆ๋ €๋‹ค๋ฉด 2๋“ฑ์ธ "soe" ์„ ์ˆ˜๊ฐ€ 1๋“ฑ์ธ "mumu" ์„ ์ˆ˜๋ฅผ ์ถ”์›”ํ–ˆ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ฆ‰ "soe" ์„ ์ˆ˜๊ฐ€ 1๋“ฑ, "mumu" ์„ ์ˆ˜๊ฐ€ 2๋“ฑ์œผ๋กœ ๋ฐ”๋€๋‹ˆ๋‹ค.
์„ ์ˆ˜๋“ค์˜ ์ด๋ฆ„์ด 1๋“ฑ๋ถ€ํ„ฐ ํ˜„์žฌ ๋“ฑ์ˆ˜ ์ˆœ์„œ๋Œ€๋กœ ๋‹ด๊ธด ๋ฌธ์ž์—ด ๋ฐฐ์—ด players์™€ ํ•ด์„ค์ง„์ด ๋ถ€๋ฅธ ์ด๋ฆ„์„ ๋‹ด์€ ๋ฌธ์ž์—ด ๋ฐฐ์—ด callings๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ๊ฒฝ์ฃผ๊ฐ€ ๋๋‚ฌ์„ ๋•Œ ์„ ์ˆ˜๋“ค์˜ ์ด๋ฆ„์„ 1๋“ฑ๋ถ€ํ„ฐ ๋“ฑ์ˆ˜ ์ˆœ์„œ๋Œ€๋กœ ๋ฐฐ์—ด์— ๋‹ด์•„ return ํ•˜๋Š” solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.
 

๐Ÿ’ก  ์•„์ด๋””์–ด

1. ์ด๋ฆ„์ด ๋ถˆ๋ฆฌ๋ฉด ๋ฐฐ์—ด์—์„œ ์•ž ์ฃผ์ž์™€ ์ด๋ฆ„์ด ๋ถˆ๋ฆฐ ์ฃผ์ž๋ฅผ ๋ฐ”๊ฟ”์ค€๋‹ค => ์‹œ๊ฐ„ ์ดˆ๊ณผ ๋‚  ๊ฑฐ ์•Œ๊ณ  ์žˆ์—ˆ๋Š”๋ฐ ์ผ๋‹จ ํ•ด๋ดค๋‹คใ…Žใ…Ž..
๊ฒฐ๊ณผ๋Š” ์–ด๋–ป๊ฒŒ๋“  ๋‚˜์˜ค์ง€๋งŒ ํ…Œ์ผ€ 4๊ฒฝ์šฐ ์‹œ๊ฐ„์ดˆ๊ณผ
 
2. ๋“ฑ์ˆ˜๋ฅผ ๋ฏธ๋ฆฌ ๊ฐ์ฒด๋กœ ์ €์žฅํ•ด๋‘ฌ์„œ ์ด์ค‘ ํฌ๋ฌธ ๋Œ์ง€ ์•Š๊ฒŒ ๊ตฌํ˜„ํ•œ๋‹ค.
 

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

// ์‹œ๊ฐ„์ดˆ๊ณผ ์ฝ”๋“œ 

function solution(players, callings) {
  for(let i=0; i<callings.length; i++) {
    let temp = 1;
    for(let j=0; j<players.length; j++) {
      if(callings[i] === players[j]) {
        temp = players[j-1];
        players[j-1] = players[j];
        players[j] = temp;
      }
    }
  }
  return players;
}

 

// ์ •๋‹ต

function solution(players, callings) {
  let rank = {};

  for (let i = 0; i < players.length; i++) {
    const key = players[i];
    const value = i;
    rank[key] = value;
  }

  for(let i=0; i<callings.length; i++){
    const idx = rank[callings[i]];  // ์ด๋ฆ„ ๋ถ€๋ฅธ ์ฃผ์ž์˜ ๋“ฑ์ˆ˜ ์ €์žฅ
    const front = players[idx-1]; // ์ด๋ฆ„ ๋ถ€๋ฅธ ์ฃผ์ž์˜ ์•ž ์ฃผ์ž ์ €์žฅ
    players[idx-1] = callings[i]; // ์•ž ์ฃผ์ž๋ฅผ ์ด๋ฆ„ ๋ถ€๋ฅธ ์ฃผ์ž๋กœ ๋ณ€๊ฒฝ
    players[idx] = front; // ์ด๋ฆ„ ๋ถ€๋ฅธ ์ฃผ์ž๋ฅผ ์•ž ์ฃผ์ž๋กœ ์ €์žฅ

    rank[callings[i]] = idx - 1; // ์ด๋ฆ„ ๋ถ€๋ฅธ ์ฃผ์ž์˜ ๋“ฑ์ˆ˜๋ฅผ ํ•œ ์ˆœ์œ„ ์•ž์œผ๋กœ
    rank[front] = idx; // ์ด๋ฆ„ ๋ถ€๋ฅธ ์ฃผ์ž์˜ ์•ž ์ฃผ์ž์˜ ๋“ฑ์ˆ˜๋ฅผ ํ•œ ์ˆœ์œ„ ๋’ค๋กœ
  }

  return players;
}