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

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํŠน์ดํ•œ ์ •๋ ฌ ๋ณธ๋ฌธ

Study/Coding Test

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํŠน์ดํ•œ ์ •๋ ฌ

Jieunny 2023. 2. 6. 14:12

๐Ÿ“Œ  ๋ฌธ์ œ

์ •์ˆ˜ n์„ ๊ธฐ์ค€์œผ๋กœ n๊ณผ ๊ฐ€๊นŒ์šด ์ˆ˜๋ถ€ํ„ฐ ์ •๋ ฌํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์ด๋•Œ n์œผ๋กœ๋ถ€ํ„ฐ์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ™๋‹ค๋ฉด ๋” ํฐ ์ˆ˜๋ฅผ ์•ž์— ์˜ค๋„๋ก ๋ฐฐ์น˜ํ•ฉ๋‹ˆ๋‹ค. ์ •์ˆ˜๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด numlist์™€ ์ •์ˆ˜ n์ด ์ฃผ์–ด์งˆ ๋•Œ numlist์˜ ์›์†Œ๋ฅผ n์œผ๋กœ๋ถ€ํ„ฐ ๊ฐ€๊นŒ์šด ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•œ ๋ฐฐ์—ด์„ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.


์ œํ•œ์‚ฌํ•ญ

  • 1 ≤ n ≤ 10,000
  • 1 ≤ numlist์˜ ์›์†Œ ≤ 10,000
  • 1 ≤ numlist์˜ ๊ธธ์ด ≤ 100
  • numlist๋Š” ์ค‘๋ณต๋œ ์›์†Œ๋ฅผ ๊ฐ–์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

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

n์—์„œ numlist์˜ ๊ฐ ์š”์†Œ๋ฅผ ๋บ€ ๊ฐ’์„ ์š”์†Œ์˜ ๊ฐ’๊ณผ ํ•จ๊ป˜ numlist๋ฐฐ์—ด์— ๋‹ด๋Š”๋‹ค.

๊ทธ ๋ฐฐ์—ด์„ ๋บ€ ๊ฐ’์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.

์ •๋ ฌ ํ›„, ๋บ€ ๊ฐ’์ด ๊ฐ™์€ ์š”์†Œ๋“ค์€ numlist์˜ ๊ฐ’์ด ํฐ ์š”์†Œ๊ฐ€ ์•ž์— ์˜ค๊ฒŒ ์ •๋ ฌํ•œ๋‹ค.

์ตœ์ข…์ ์œผ๋กœ ์ •๋ ฌ๋œ ๋ฐฐ์—ด์—์„œ numlist ๊ฐ’๋งŒ ์ˆœ์„œ๋Œ€๋กœ answer์— ๋‹ด๋Š”๋‹ค.

 

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

function solution(numlist, n) {
  var answer = [];
  let minus = [];

  for(let i of numlist){
    minus.push([i, Math.abs(n-i)]);
  }

  let minusSort = minus.sort((a, b) => {
    return a[1] - b[1];
  })

  for(let i=0; i<minusSort.length; i++){
    if(i+1<minusSort.length && minusSort[i][1] === minusSort[i+1][1]){
      if(minusSort[i+1][0] > minusSort[i][0]){
        let temp = minusSort[i][0];
        minusSort[i][0] = minusSort[i+1][0];
        minusSort[i+1][0] = temp;
      }
    }
  }

  for(let i=0; i<minusSort.length; i++){
    answer.push(minusSort[i][0]);
  }

  return answer;
}