https://school.programmers.co.kr/learn/courses/30/lessons/120880

 

๋ฌธ์ œ

 

๋ฌธ์ œ ์„ค๋ช…

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

 

์ œํ•œ ์‚ฌํ•ญ

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

 

์ž…์ถœ๋ ฅ ์˜ˆ

numlist n result
[1, 2, 3, 4, 5, 6] 4 [4, 5, 3, 6, 2, 1]
[10000,20,36,47,40,6,10,7000] 30 [36, 40, 20, 47, 10, 6, 7000, 10000]

 

 

์†Œ์Šค ์ฝ”๋“œ
# 1
def solution(numlist, n):
    # Key = ์ˆซ์ž / Value = ์ฐจ์ด
    num_diff = {}
    for num in numlist:
        num_diff[num] = abs(num-n)   

    rank = dict(sorted(num_diff.items(), key=lambda x:(x[1],-x[0])))
    
    return list(rank.keys())

 

ํ’€์ด # 1

  • num_diff ๋ผ๋Š” ๋”•์…”๋„ˆ๋ฆฌ ์ƒ์„ฑ
    • Key๊ฐ’์— numlist์˜ ์ˆซ์ž / Value๊ฐ’์— numlist ์ˆซ์ž์™€ n์˜ ์ฐจ์ด ์ž…๋ ฅ
  • rank๋ผ๋Š” ๋”•์…”๋„ˆ๋ฆฌ ์ƒ์„ฑ
    • num_diff์˜ Value(= numlist ์ˆซ์ž์™€ n์˜ ์ฐจ์ด) ๊ธฐ์ค€ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ → x[1]
    • Value๊ฐ€ ๊ฐ™๋‹ค๋ฉด Key๊ฐ€ ํฐ ๊ฐ’ ๋จผ์ € ์˜ค๋„๋ก ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ → -x[0]
  • ์ •๋ ฌ๋œ rank ๋”•์…”๋„ˆ๋ฆฌ์˜ Key๊ฐ’(=numlist์˜ ์ˆซ์ž) ์ถœ๋ ฅ

 

# 2
def solution(numlist, n):
    numlist.sort(key=lambda x:(abs(n-x), -x))
    return numlist

 

ํ’€์ด #2

  • numlist ์ˆซ์ž์™€ n์˜ ์ฐจ์ด ์˜ค๋ฆ„์ฐจ์ˆœ / numlist ์ˆซ์ž ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ
  • ์ •๋ ฌ๋œ numlist ์ถœ๋ ฅ

 

 

์ฒซ ๋ฒˆ์งธ ํ’€์ด๋Š” '์ฐจ์ด๊ฐ’ ๋งŒ๋“ค๊ธฐ → ์ฐจ์ด๊ฐ’๊ณผ ์ˆซ์ž๋ฅผ ๋”•์…”๋„ˆ๋ฆฌ์— ๋„ฃ๊ธฐ → ์ฐจ์ด๊ฐ’ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ → ์ •๋ ฌ๋œ ๋”•์…”๋„ˆ๋ฆฌ์—์„œ ํ‚ค ๊ฐ’ ์ถœ๋ ฅํ•˜๊ธฐ' ์˜ ๊ณผ์ •์„ ๊ฑฐ์น˜๊ณ  ๋‘ ๋ฒˆ์งธ ํ’€์ด๋Š” '์ฐจ์ด๊ฐ’ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ'๊ฐ€ ๋์ด๋‹ค. ์›๋ฆฌ?๋Š” ๊ฐ™์ง€๋งŒ ์–ผ๋งˆ๋‚˜ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ํ‘œํ˜„ํ•˜๋Š”์ง€์— ๋”ฐ๋ผ์„œ ์ฝ”๋“œ๊ฐ€ ์ข€ ๋” ๊น”๋”ํ•ด์ง€๋Š” ๊ฒƒ ๊ฐ™๋‹ค. ๋ฌธ์ œ๋ฅผ ๋งŽ์ด ํ’€์–ด๋ด์•ผ๊ฒ ๋‹ค๊ณ  3928490๋ฒˆ์งธ ๋‹ค์งํ•˜๋Š” ์ค‘์ด๋‹ค. 

+ Recent posts