Python:
每日一刷-Count of Smaller Numbers After Self
[每日一刷] (Count of Smaller Numbers After Self)
You are given an integer array nums and you have to return a new counts array.
The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:
Given nums = [5, 2, 6, 1]
Return the array [2, 1, 1, 0]
解题思路
这题其实又是一个有关区间的题,每次都找当前值后面有多少个比它小的数。因此马上可以想到用线段树。
这道题其实就是值线段树的简单应用,线段树结点中存储一个区间内有多少个值,然后每次查询后修改线段树。
这题主要就是各种边界条件比较多,下次要注意。
Python:
每日一刷-Range-Sum-Query-2D-Immutable
[每日一刷] (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).
Example:
Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12
解题思路
这题思路和一维的时候一致,可以使用动态规划也可以使用线段树。就这题来说使用动态规划会简单很多。
思路就是用dp[i][j]表示从(0, 0)到(i, j)的和
Python: