๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] ๋ฌธ์ž์—ด ๋‚ด ๋งˆ์Œ๋Œ€๋กœ ์ •๋ ฌํ•˜๊ธฐ Programmers(Lv.1)

by seolhee2750 2021. 6. 17.
๋ฌธ์ œ ์„ค๋ช…

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

 

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

 

์ž…์ถœ๋ ฅ ์˜ˆ
strings n return
["sun", "bed", "car"] 1 ["car", "bed", "sun"]
["abce", "abcd", "cdx"] 2 ["abcd", "abce", "cdx"]

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import Foundation

func solution(_ strings:[String], _ n:Int) -> [String] {
    return strings.sorted(){Array($0)[n] == Array($1)[n] ? $0 < $1 :  Array($0)[n] < Array($1)[n]}
}
  • sorted ์‚ฌ์šฉํ•˜์—ฌ ์ •๋ ฌํ•˜์˜€๋Š”๋ฐ, ํด๋กœ์ €๋ฅผ ์ด์šฉํ•ด์„œ ์ •๋ ฌ์˜ ๋‚ด์šฉ์„ ์ž‘์„ฑํ•ด์ฃผ์—ˆ๋‹ค.
  • ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ๋ฅผ ๋ฐฐ์—ด๋กœ ๋ฐ”๊พธ๊ณ , ์•ž ๋ฐฐ์—ด์ด ๋’ท ๋ฐฐ์—ด์˜ n๋ฒˆ์งธ ๊ธ€์ž๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ ๋ฐฐ์—ด ์ž์ฒด๋กœ ์ •๋ ฌ, ๋‹ค๋ฅผ ๊ฒฝ์šฐ์—” n๋ฒˆ์งธ ๊ธ€์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ฒ˜์Œ์— ์–ด๋–ป๊ฒŒ ํ’€์–ด์•ผ ํ•  ์ง€ ์ „ํ˜€ ๊ฐ์„ ์žก์ง€ ๋ชปํ•ด์„œ ๊ฒฐ๊ตญ ๋‹ค๋ฅธ ๋ถ„์˜ ํ’€์ด๋ฅผ ์ฐธ๊ณ ํ•ด์„œ ํ’€์—ˆ๋Š”๋ฐ, sorted์— ํด๋กœ์ €๋ฅผ ์ด์šฉํ•˜๋‹ˆ ์™„๋ฒฝํ•œ ํ’€์ด๊ฐ€ ๋‚˜์™”๋‹ค,,;;
  • ํด๋กœ์ € ์‚ฌ์šฉ์— ๋Œ€ํ•ด ๊ณต๋ถ€๊ฐ€ ๋งŽ์ด ํ•„์š”ํ•  ๋“ฏ ํ•˜๋‹ค.

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€