[ํ๋ก๊ทธ๋๋จธ์ค] K๋ฒ์งธ์
<๋ฌธ์ >
<์ ๋ต์ง๊ธฐ>
๋ฌธ์ ์์ ํ๋ผ๋ ๋๋ก๋ง ํ๋ฉด ๋๋..? ๋ฌธ์ ๊ฐ๋ค. ํฌ๊ฒ ์๊ฐํด์ผ ํ ๋ถ๋ถ์ ์์ ๊ฒ ๊ฐ์๊ณ , ํ๊ฐ์ง ์ฃผ์ํด์ผ ํ ๋ถ๋ถ์ commands์์ ๊ฐ ์์(๋ฐฐ์ด)์ ๊ฐ๋ค์ "n๋ฒ์งธ" ์ด์ง ์ธ๋ฑ์ค๊ฐ "n"์์ ๋ํ๋ด๋ ๊ฒ์ด ์๋๋ฏ๋ก, Out Of Index Error๋ฅผ ํผํ๊ธฐ ์ํด commands์ ๊ฐ ์์๋ค์ ์ธ๋ฑ์ค๋ก ํ์ฉํ๊ธฐ ์ํด ๋ชจ๋ -1์ ์ฒ๋ฆฌํ ํ์ ์ฌ์ฉ ํด์ผ ํ๋ค๋ ์ ์ด๋ค.
<์ฝ๋>
import Foundation
func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
var result: [Int] = []
for command in commands {
var orderArray = array[command[0]-1...command[1]-1].sorted()
result.append(orderArray[command[2]-1])
}
return result
}
<Lesson Learned>
์ค๋๋ง์ ์๊ณ ๋ฆฌ์ฆ์ ๋ค์ ์์ํ๋ ์ (๋ํ์๋ ์ดํ๋ก ์ํ์ผ๋.. 6๋ ๋ง? ์ธ๊ฑฐ๊ฐ๋ค ใ ), Swift๋ฅผ ๊ณต๋ถํ๊ธฐ ์ํด ์์ํ๋ค๋ ์ ๋๋ฌธ์ Level 1 ๋์ด๋ ๋ฌธ์ ์์ ๊ณจ๋ผํ๊ณ ์๋ค..ํํ ๐ ๊ทธ์ค์์๋ ์ด ๋ฌธ์ ๋ ์ฌ์ ๋ ๋ฌธ์ ๊ฐ๋ค. ๊ทธ๋ฌ๋.... ์ญ์ ๋ค๋ฅธ์ฌ๋์ ํ์ด๋ฅผ ๋ดค์๋ ์ด๋ด ์๋ ์๊ตฌ๋.. ์ถ์๊ฑด ์๋ค ใ ใ ์ด๋ฒ์๋ map์ ์ฌ์ฉํ๋ค๋ฉด result๋ผ๋ ๋ฐฐ์ด๋ ํ์์์์ ๊ฒ ๊ฐ๊ณ , ์ฝ๋๋ ๊ฐ๊ฒฐํ์ ๊ฒ ๊ฐ๋ค. ์๋์ฒ๋ผ ํ๋ฒ ๋๋ ค๋ดค๋๋ฐ, ์ ๋๋ค ๐๐ ๋์ด๋ ์ฌ๋ ค์ ๋ฌธ์ ํ๋ ค๋ฉด map, filter์ ๋นจ๋ฆฌ ์ต์ํด์ง ํ์๊ฐ ์๋ค. ๐
import Foundation
func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
return commands.map { array[$0[0]-1...$0[1]-1].sorted()[$0[2]-1] }
}
์ถ์ฒ : ํ๋ก๊ทธ๋๋จธ์ค K๋ฒ์งธ์