[LeetCode] 519. Random Flip Matrix

Chobby·2026년 3월 19일

LeetCode

목록 보기
1039/1045

😎풀이

  1. m * n의 2차원 배열을 Flatten 한다는 개념을 추상화하여 this.total 선언
  2. flip 호출 시
    2-1. flatten 수 중 랜덤한 수 pick
    2-2. 전체 수를 감소시키고, 현재 수가 이미 선택되어 다른 수를 대신 할당했는지 확인
    2-3. 현재 뽑을 수 있는 가장 큰 수가 이미 선택되어 다른 수를 할당했는지 확인
    2-4. 랜덤하게 뽑았던 수를 사용했으므로, 가장 큰 다른 수 할당
    2-5. 2차원 배열의 개념을 원복하여 행렬을 반환
  3. reset 호출 시
    3-1. board를 새로 flatten
    3-2. 뽑은 수가 없으므로 메모리 초기화
class Solution {
    private total: number
    private rows: number
    private cols: number
    private map: Map<number, number>
    constructor(m: number, n: number) {
        this.rows = m
        this.cols = n
        this.total = m * n
        this.map = new Map<number, number>()
    }

    flip(): number[] {
        const rand = Math.floor(Math.random() * this.total)
        this.total--
        const idx = this.map.get(rand) ?? rand
        const last = this.map.get(this.total) ?? this.total
        this.map.set(rand, last)
        return [Math.floor(idx / this.cols), idx % this.cols]
    }

    reset(): void {
        this.total = this.rows * this.cols
        this.map = new Map<number, number>()
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글