Loading

LeetCode problem#1476

Subrectangle Queries

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

52 lines
1class SubrectangleQueries {
2    private int[][] rectangle;
3
4    public SubrectangleQueries(int[][] rectangle) {
5        this.rectangle = rectangle;
6    }
7    
8    public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
9        int startRow;
10        int endRow;
11        int startCol;
12        int endCol;
13
14        // You can actually do away with these because the constraints
15        // guarantee 0 <= row1 <= row2 < rows
16        // and 0 <= col1 <= col2 < cols
17        if (row1 < row2) {
18            startRow = row1;
19            endRow = row2;
20        }
21        else {
22            startRow = row2;
23            endRow = row1;
24        }
25
26        if (col1 < col2) {
27            startCol = col1;
28            endCol = col2;
29        }
30        else {
31            startCol = col2;
32            endCol = col1;
33        }
34
35        for (int i = startRow; i <= endRow; i++) {
36            for (int j = startCol; j <= endCol; j++) {
37                rectangle[i][j] = newValue;
38            }
39        }
40    }
41    
42    public int getValue(int row, int col) {
43        return rectangle[row][col];
44    }
45}
46
47/**
48 * Your SubrectangleQueries object will be instantiated and called as such:
49 * SubrectangleQueries obj = new SubrectangleQueries(rectangle);
50 * obj.updateSubrectangle(row1,col1,row2,col2,newValue);
51 * int param_2 = obj.getValue(row,col);
52 */

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.