๐Ÿ’ก Level 1 | ๋ฌธ์ž์—ด ๋‚ด ๋งˆ์Œ๋Œ€๋กœ ์ •๋ ฌํ•˜๊ธฐ (JavaScript)

rimmzยท2022๋…„ 7์›” 2์ผ
0

programmers

๋ชฉ๋ก ๋ณด๊ธฐ
12/15
post-thumbnail

๐Ÿ“Œ ๋ฌธ์ œ

๋ฌธ์ž์—ด๋กœ ๊ตฌ์„ฑ๋œ ๋ฆฌ์ŠคํŠธ strings์™€, ์ •์ˆ˜ n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๊ฐ ๋ฌธ์ž์—ด์˜ ์ธ๋ฑ์Šค n๋ฒˆ์งธ ๊ธ€์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด strings๊ฐ€ ["sun", "bed", "car"]์ด๊ณ  n์ด 1์ด๋ฉด ๊ฐ ๋‹จ์–ด์˜ ์ธ๋ฑ์Šค 1์˜ ๋ฌธ์ž "u", "e", "a"๋กœ strings๋ฅผ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.

  • strings๋Š” ๊ธธ์ด 1 ์ด์ƒ, 50์ดํ•˜์ธ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
  • strings์˜ ์›์†Œ๋Š” ์†Œ๋ฌธ์ž ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.
  • strings์˜ ์›์†Œ๋Š” ๊ธธ์ด 1 ์ด์ƒ, 100์ดํ•˜์ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค.
  • ๋ชจ๋“  strings์˜ ์›์†Œ์˜ ๊ธธ์ด๋Š” n๋ณด๋‹ค ํฝ๋‹ˆ๋‹ค.
  • ์ธ๋ฑ์Šค 1์˜ ๋ฌธ์ž๊ฐ€ ๊ฐ™์€ ๋ฌธ์ž์—ด์ด ์—ฌ๋Ÿฟ ์ผ ๊ฒฝ์šฐ, ์‚ฌ์ „์ˆœ์œผ๋กœ ์•ž์„  ๋ฌธ์ž์—ด์ด ์•ž์ชฝ์— ์œ„์น˜ํ•ฉ๋‹ˆ๋‹ค.

https://programmers.co.kr/learn/courses/30/lessons/12915

๐Ÿ“ ๋ฌธ์ œ ํ’€์ด

function solution(strings, n) {
  return strings.sort((a, b) => {
    if (a[n] < b[n]) return -1; // a[n]์ด b[n] ๋ณด๋‹ค ์ž‘์„ ๊ฒฝ์šฐ ์•ž์œผ๋กœ ๋ณด๋‚ธ๋‹ค.
    if (a[n] > b[n]) return 1; // a[n]์ด b[n] ๋ณด๋‹ค ํด ๊ฒฝ์šฐ ๋’ค๋กœ ๋ณด๋‚ธ๋‹ค.

    if (a[n] === b[n]) {
      // ์ฃผ์–ด์ง„ ๋ฌธ์ž๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ
      // ๋ฌธ์ž์—ด์„ ๋น„๊ตํ•ด ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
      if (a < b) return -1;
      if (a > b) return 1;
    }

    return strings;
  });
}

๐ŸŒฟ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

function solution(strings, n) {
  // strings ๋ฐฐ์—ด
  // n ๋ฒˆ์งธ ๋ฌธ์ž์—ด ๋น„๊ต
  return strings.sort((s1, s2) =>
    s1[n] === s2[n] ? s1.localeCompare(s2) : s1[n].localeCompare(s2[n])
  );
}

localeCompare(compareString, locales, options)

  • ์ฐธ์กฐ ๋ฌธ์ž์—ด์ด ์ •๋ ฌ ์ˆœ์„œ์—์„œ ์•ž ๋˜๋Š” ๋’ค์— ์˜ค๋Š”์ง€ ๋˜๋Š” ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด๊ณผ ๊ฐ™์€์ง€๋ฅผ ์ˆซ์ž๋กœ ๋ฐ˜ํ™˜
  • referenceStr ์ด compareString ๋ณด๋‹ค ๋จผ์ € ๋ฐœ์ƒ ํ•˜๋ฉด ์Œ์ˆ˜
  • compareString ๋‹ค์Œ์— referenceStr ์ด ๋ฐœ์ƒ ํ•˜๋ฉด ์–‘์ˆ˜
  • ๋™์ผํ•˜๋ฉด 0 ์„ ๋ฐ˜ํ™˜ ํ•ฉ๋‹ˆ๋‹ค.
'a'.localeCompare('b') // -1 , 
'b'.localeCompare('a') // 1
'c'.localeCompare('c') // 0
profile
#์˜์š•๋„˜์น˜๋Š”#๐Ÿ’ป#โœจ#FE#๐Ÿ’ช๐Ÿป

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