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

[Swift Algorithm] ์ตœ๋Œ“๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’ Programmers(Lv.2)

by seolhee2750 2021. 7. 8.
๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ž์—ด s์—๋Š” ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋œ ์ˆซ์ž๋“ค์ด ์ €์žฅ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. str์— ๋‚˜ํƒ€๋‚˜๋Š” ์ˆซ์ž ์ค‘ ์ตœ์†Œ๊ฐ’๊ณผ ์ตœ๋Œ€๊ฐ’์„ ์ฐพ์•„ ์ด๋ฅผ "(์ตœ์†Œ๊ฐ’) (์ตœ๋Œ€๊ฐ’)"ํ˜•ํƒœ์˜ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•˜์„ธ์š”.
์˜ˆ๋ฅผ๋“ค์–ด s๊ฐ€ "1 2 3 4"๋ผ๋ฉด "1 4"๋ฅผ ๋ฆฌํ„ดํ•˜๊ณ , "-1 -2 -3 -4"๋ผ๋ฉด "-4 -1"์„ ๋ฆฌํ„ดํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

์ œํ•œ ์กฐ๊ฑด
  • s์—๋Š” ๋‘˜ ์ด์ƒ์˜ ์ •์ˆ˜๊ฐ€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
s return
"1 2 3 4" "1 4"
"-1 -2 -3 -4" "-4 -1"
"-1 -1" "-1 -1"

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ s:String) -> String {
    let arr = s.components(separatedBy: " ").map{Int($0)!}
    return String(arr.min()!) + " " + String(arr.max()!)
}
  • ์šฐ์„  ๊ณต๋ฐฑ์œผ๋กœ ๋‚˜๋ˆ  ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค๊ณ , ๋ชจ๋‘ Int๋กœ ์บ์ŠคํŒ…ํ•ด์ฃผ์—ˆ๋‹ค.
  • ๋ฐฐ์—ด์˜ ์ตœ์†Ÿ๊ฐ’๊ณผ ์ตœ๋Œ“๊ฐ’, ๊ทธ๋ฆฌ๊ณ  ์ค‘๊ฐ„์— ๊ณต๋ฐฑ์„ ๋„ฃ์–ด ๋ฌธ์ž์—ด๋กœ ๋ฐ˜ํ™˜ํ•ด์ฃผ์—ˆ๋‹ค.
  • return๋ฌธ ํ•œ ์ค„๋กœ๋„ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•˜์ง€๋งŒ ๊ฐ€๋…์„ฑ์„ ์œ„ํ•ด ๋‘ ์ค„๋กœ ์ž‘์„ฑํ–ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ฒ˜์Œ์— min()๊ณผ max()์— ๊ฐ•์ œ์ถ”์ถœ์„ ์•ˆํ•ด์คฌ๋Š”๋ฐ, ์•Œ๊ณ ๋ณด๋‹ˆ ์˜ต์…”๋„๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ผ์„œ ๊ฐ•์ œ์ถ”์ถœ์ด ํ•„์š”ํ–ˆ๋‹ค.!!

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€