TIL #52

loci·2024년 6월 21일
0

TIL

목록 보기
50/103


할인 행사

원하는 제품과 수량이 할인품목에서 연속적으로 10개가 나올때 카운트를 하나씩해서 총 몇번의 카운트가 되는지 반환해야 한다.

시간내에 못풀어서 다른 코드를 참고해 풀어주었다.
제품과 수량을 map으로 합쳐준 후 discountMap을 새로 만들어서 모든 제품이 원하는 제품의 수량보다 많으면 answer를 카운트 해주고 반복이 끝나면 answer를 반환해준다.


나의코드

class Solution {
    fun solution(want: Array<String>, number: IntArray, discount: Array<String>): Int {
        var answer: Int = 0
        var map = mutableMapOf<String, Int>()
        
        for(i in want.indices){
            map[want[i]] = number[i]
        }
        
        for(i in 0..discount.size -10){
            val disMap = mutableMapOf<String,Int>()
            
            for(j in i until i + 10){
                disMap[discount[j]] = disMap.getOrDefault(discount[j], 0) + 1
            }
            
            if(map.all {(item, count) -> disMap.getOrDefault(item, 0) >= count}){
                answer++
            }
        }
            
        return answer
    }
}

다른사람의 코드

class Solution {
    fun solution(want: Array<String>, number: IntArray, discount: Array<String>): Int {
        var count: Int = 0

        for (offset in 0 until discount.size - 10 + 1) {
            val dis = discount.copyOfRange(offset, offset + 10)

            var flag = true
            for (i in want.indices) {
                val c = dis.count { it == want[i] }
                if (number[i] != c) {
                    flag = false
                    break
                }
            }

            if (flag) count++
        }

        return count
    }
}
profile
편리한 개발자

0개의 댓글