[LeetCode] 2352. Equal Row and Column Pairs(Kotlin)

0

LeetCode

목록 보기
56/58
post-thumbnail

[LeetCode] 2352. Equal Row and Column Pairs(Kotlin)

풀이

// input
grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]

// values
rowMap: {0=[3, 1, 2, 2], 1=[1, 4, 4, 5], 2=[2, 4, 2, 2], 3=[2, 4, 2, 2]}
colMap: {0=[3, 1, 2, 2], 1=[1, 4, 4, 4], 2=[2, 4, 2, 2], 3=[2, 5, 2, 2]}
rowCountMap: {[3, 1, 2, 2]=1, [1, 4, 4, 5]=1, [2, 4, 2, 2]=2}
colCountMap: {[3, 1, 2, 2]=1, [1, 4, 4, 4]=1, [2, 4, 2, 2]=1, [2, 5, 2, 2]=1}

// output
3
class Solution {
    fun equalPairs(grid: Array<IntArray>): Int {
        val n = grid.size
        val rowMap: MutableMap<Int, String> = mutableMapOf()
        val colMap: MutableMap<Int, String> = mutableMapOf()

        // init row map
        for(r in 0 until n){
            rowMap[r] = grid[r].toList().toString()
        }
        // init column map
        for(c in 0 until n){
            colMap[c] = mutableListOf<Int>().apply{
                for(r in 0 until n) add(grid[r][c])
            }.toString()
        }
        
        // count identical strings in maps
        val rowCountMap = rowMap.values.groupingBy{it}.eachCount() // MutableMap<String, Int>
        val colCountMap = colMap.values.groupingBy{it}.eachCount() // MutableMap<String, Int>
        
        var answer: Int = 0
        for(row in rowCountMap.keys){
            if(colCountMap.containsKey(row)){
                answer += rowCountMap[row]!! * colCountMap[row]!!
            }
        }
        return answer
    }
}
profile
Be able to be vulnerable, in search of truth

0개의 댓글