(코딩테스트) 모의고사

2024. 4. 16. 11:03개발자 과정/Kotlin

https://n-pureun.tistory.com/37

 

풀이의 선택과정

1. 아주 옛날에 풀었던 문제다.

2. 좀 다르게 풀어볼까 했지만, 이미 충분한 로직같다.

3. 그래서 다듬는 정도로만 풀었다.

 

정답풀이

class Solution {
    private fun setList():List<IntArray> =
        listOf(intArrayOf(1, 2, 3, 4, 5),
            intArrayOf(2, 1, 2, 3, 2, 4, 2, 5),
            intArrayOf(3, 3, 1, 1, 2, 2, 4, 4, 5, 5))

    fun solution(answers: IntArray): IntArray {
        var answer = intArrayOf()
        val score= mutableListOf(0,0,0)
        for(i in answers.indices)
        {
            setList().forEachIndexed { j, it ->
                if(answers[i]==it[i%it.size]) score[j]++ }
        }
        
        for(i in score.indices) if(score[i]==score.maxOf { it }) answer+=i+1
        return answer.sortedArray()
    }
}

 

핵심로직

if(answers[i]==it[i%it.size]) score[j]++ }

= i%arrSize 연산을 통해 원형큐처럼 index가 올라가도 배열안에서 빙글빙글 순회한다.

 

for(i in score.indices) if(score[i]==score.maxOf { it }) answer+=i+1

= 그냥 max함수를 쓰면 원소를 하나만 뽑아올 것이다. 그래서 list를 순회하며 max와 값이 같은 원소index를 기록한다.

  이것으로 중복된 최대값저장 가능해진다.