[LeetCode]304. Range Sum Query 2D - Immutable
2016-04-13 13:53
447 查看
Problem Description
[]https://leetcode.com/problems/range-sum-query-2d-immutable/]Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
思路
DP ,越简单的题,越是容易WA。。。。Code
package q304; public class NumMatrix { private int[][] sum; private int m = 0, n = 0; public NumMatrix(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return; } m = matrix.length; n = matrix[0].length; sum = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + matrix[i - 1][j - 1]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { if (m == 0 || n == 0) return -1; if (row1 >= m || row1 < 0) return -1; if (row2 >= m || row2 < 0) return -1; if (col1 >= n || row2 < 0) return -1; if (col2 >= n || row2 < 0) return -1; return sum[row2 + 1][col2 + 1] - sum[row2 + 1][col1] - sum[row1][col2 + 1] + sum[row1][col1]; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解