์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜7] ์žฅ๋‚œ๊พธ๋Ÿฌ๊ธฐ ํ˜„์ˆ˜ (Javascript)

์€์ง„ 2021. 6. 27. 20:54

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜7] ์žฅ๋‚œ๊พธ๋Ÿฌ๊ธฐ ํ˜„์ˆ˜ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-27

1. ์ •๋ ฌ์ด ๋˜์–ด ์žˆ๋Š”๋ฐ ๋‘ ์ˆ˜์˜ ์œ„์น˜๊ฐ€ ๋ฐ”๋€Œ์—ˆ์Œ

  • ๋ฐ”๋€ ์œ„์น˜์˜ ์ธ๋ฑ์Šค๋ฅผ ์ถœ๋ ฅ

2. sort()ํ•œ ๋ฐฐ์—ด๊ณผ ๊ทธ๋ ‡์ง€ ์•Š์€ ๋ฐฐ์—ด์„ ๋น„๊ตํ•˜์—ฌ, ๋‹ค๋ฅธ ๋ถ€๋ถ„์ด ์žˆ์œผ๋ฉด

  • ๋ฐฉ๋ฒ• 1. ๋ฐฐ์—ด์— pushํ•œ ๋’ค join(' ')
  • ๋ฐฉ๋ฒ• 2. ๋ฌธ์ž์—ด res += ${x} --> ์ˆซ์ž ๊ฐ„ ๊ณต๋ฐฑ์ฒ˜๋ฆฌํ•ด์•ผ ํ•จ

3. ๋‘ ๋ฐฐ์—ด ๋น„๊ต๋Š” forEach() map() filter()

  • filter๊ฐ€ ์ง๊ด€์  ๋กœ์ง์ผ ๊ฒƒ
  • arr์™€ ์ •๋ ฌํ•œ arr๋ฅผ ๋น„๊ตํ•˜์—ฌ ๋‘ ์›์†Œ๊ฐ€ ๋‹ค๋ฅธ ๊ฒฝ์šฐ return

๋ฌธ์ œ์ 
return ํ•  ๊ฐ’์ด arr์˜ ์›์†Œ๊ฐ€ ์•„๋‹ˆ๋ผ index

4. forEach() ๋˜๋Š” map()์„ ์‚ฌ์šฉ

  • arr์™€ ์ •๋ ฌํ•œ arr๋ฅผ ๋น„๊ตํ•˜์—ฌ ๋‘ ๊ฐ’์ด ๋‹ค๋ฅธ ๊ฒฝ์šฐ res.push()
  • res์— ์ˆœ์„œ์ •๋ณด๋ฅผ ์ €์žฅํ•ด์•ผ ํ•˜๋ฏ€๋กœ res.push(i+1);
  • return res.join(' ');


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-27

function solution(arr) {
    let res = [];
    let sorted = arr.slice().sort((a, b) => a-b);

    sorted.forEach((v, i) => {
        if (v !== arr[i]) res.push(i+1);
    });

    return res.join(' ');
}