Skip to main content

2661.js

/** ------------------------------------------------------------------------------
*
* 2661. First Completely Painted Row or Column
* Topics: Hash Map, Matrix
* 릿코드 링크: https://leetcode.com/problems/first-completely-painted-row-or-column/?envType=daily-question&envId=2025-01-20
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} arr
* @param {number[][]} mat
* @return {number}
*/
var firstCompleteIndex = function (arr, mat) {
const m = mat.length
const n = mat[0].length

const rowsBingo = Array.from({ length: m }, () => 0)
const colsBingo = Array.from({ length: n }, () => 0)
const map = new Map()

for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
map.set(mat[i][j], [i, j])
}
}

for (let i = 0; i < arr.length; i++) {
const [row, col] = map.get(arr[i])

rowsBingo[row]++
colsBingo[col]++

if (rowsBingo[row] === n || colsBingo[col] === m) return i
}
return -1
}

/**
* 시간복잡도는 똑같은데 런타임 속도가 좀 더 빠름
*/
var firstCompleteIndex = function (arr, mat) {
const n = mat.length,
m = mat[0].length
const pos = Array(n * m)
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) pos[mat[i][j]] = [i, j]
}
let mps_row = Array(n).fill(0)
let mps_col = Array(m).fill(0)
for (let i = 0; i < arr.length; i++) {
const [r, c] = pos[arr[i]]
mps_row[r]++
mps_col[c]++
if (mps_row[r] === m || mps_col[c] === n) return i
}
}

console.log(
firstCompleteIndex(
[1, 3, 4, 2],
[
[1, 4],
[2, 3],
],
),
)