CT With Kotlin
[Level 1] 푸드 파이트 대회 - refactor
탱구리몬
2024. 3. 5. 10:11
// Time: 24.29 ms, Memory: 64 MB
fun solution(food: IntArray): String {
var answer = StringBuilder()
var round = 1
// 첫 번째 인덱스를 제외하고 roof 돌리기
food.sliceArray(IntRange(1, food.size - 1)).map {
val canFoodCountByRound = it / 2
answer.append((round.toString()).repeat(canFoodCountByRound))
round += 1
if (round == food.size) {
val answerBackup = answer.reversed()
answer.append(0)
answer.append(answerBackup)
return@map
}
}
return answer.toString()
}
개선한 부분(변경점)
1. 불필요한 round 변수 제거
2. 데이터를 변환하는 과정이 없기 때문에, map 보다는 for 사용하기 - 이 부분에서 시간 및 메모리 단축 된 듯
3. append에서 vararg 활용하여 한 번에 append 하기
4. sliceArray로 제일 처음 index를 자르지 않고 roof 내에서 if문으로 continue 처리하기
// Time: 7.77 ms, Memory: 61.4 MB
fun solution(food: IntArray): String {
var answer = StringBuilder()
for ((index, i) in food.withIndex()) { // 1. round 제거후 index 활용, 2, 4
if (index == 0) continue
val canFoodCountByRound = i / 2
answer.append((index.toString()).repeat(canFoodCountByRound))
if (index == food.size - 1) {
val reverseAnswer = answer.reverse()
answer.append(0, reverseAnswer) // 3. vararg 활용
}
}
return answer.toString()
}