TIL/Algorithm

[99클럽 코테 스터디 26일차 TIL] ㅣLeetCode | 1476. Subrectangle Queries

ujum 2024. 6. 14. 20:27
728x90

26일차 array

Problem

https://leetcode.com/problems/subrectangle-queries/

 

Sol

✅ 주어진 메소드 2개를 이용하여 class SubrectangleQueries를 완성하는 문제

class SubrectangleQueries 는 'rows x cols' 크기의 직사각형을 정수 matrix 로 받아들입니다.

 

method 1) updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)

  • 왼쪽 위 좌표가 (row1, col1)이고 오른쪽 아래 좌표가 (row2, col2)인 부분 직사각형의 모든 값을 newValue로 업데이트
  • 지정된 부분 직사각형의 범위 내의 모든 값을 새로운 값으로 변경한다는 의미

method 2) getValue(int row, int col)

  • 직사각형에서 특정 좌표 (row, col)에 있는 값 반환

 

 

해결 방법

👀 예시를 통해 문제를 파악하고 입력이 들어왔을때 함수가 잘 동작하도록 구현했습니다.

1. SubrectangleQueries
- 2차원 배열로 초기화

2. updateSubrectangle
- 매개변수 (self, row1: int, col1: int, row2: int, col2: int, newValue: int)
- 배열로 초기화된 rectangle에서 왼쪽 위 좌표가 (row1, col1), 오른쪽 아래 좌표가 (row2, col2)인 부분 직사각형(sub rectangle)의 값을 모두 newValue로 바꿉니다.
- 반복문을 사용하여 주어진 범위내를 순회할 수 있습니다.
  : 바깥에서 row 순회, 안에서 col 순회 -> newValue로 업데이트

3. getValue
- getValue에 들어온 (row, col)의 값을 반환합니다. 

 


✔ Answer

class SubrectangleQueries:

    def __init__(self, rectangle: List[List[int]]):
        self.rectangle = rectangle

    def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
        # sub rectangle -> newvalue
        for i in range(row1, row2 + 1):
            for j in range(col1, col2 + 1):
                self.rectangle[i][j] = newValue

    def getValue(self, row: int, col: int) -> int:
        # return the current value 
        return self.rectangle[row][col]


# Your SubrectangleQueries object will be instantiated and called as such:
# obj = SubrectangleQueries(rectangle)
# obj.updateSubrectangle(row1,col1,row2,col2,newValue)
# param_2 = obj.getValue(row,col)






💬 소감

문제를 이해하고는 푸는데 오래걸리지 않았어요. 근데 다른 사람들의 풀이를 보니까 코드의 효율이나 다양한 방법으로 접근해본게 보여서 또 한대 맞은 기분이에요. 특히 뭐 바로 업데이트하는 게 아니라 데이터를 목록에 추가하는 방법과 histories를 사용한 분이 있었는데 어찌 저런 생각을 하시나 싶었어요👍 신기합니다.