1.子矩形查询
class SubrectangleQueries {
int [][]myRectangle;
public SubrectangleQueries(int[][] rectangle) {
int row=rectangle.length; //行数
myRectangle=new int[row][];
for(int i=0;i<rectangle.length;i++){
myRectangle[i]=new int[rectangle[i].length];
for(int j=0;j<rectangle[i].length;j++){
myRectangle[i][j]=rectangle[i][j];
}
}
}
public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
for(int i=0;i<=row2-row1;i++){
for(int j=0;j<=col2-col1;j++){
myRectangle[i+row1][j+col1]=newValue;
}
}
}
public int getValue(int row, int col) {
return myRectangle[row][col];
}
}
/**
* Your SubrectangleQueries object will be instantiated and called as such:
* SubrectangleQueries obj = new SubrectangleQueries(rectangle);
* obj.updateSubrectangle(row1,col1,row2,col2,newValue);
* int param_2 = obj.getValue(row,col);
*/
3. 直方图的水量
动态规划:
//有一种思路:可以计算出每个长方体上部的蓄水量。
//如何计算:可以求该处左侧最高长方体和右侧最高长方体,取最小值-该长方体高度
//如果取值为负那就是不蓄水,如果取值为正那该值就是它上面的蓄水量。
//重点是如何确定最大的位置;
其实动态规划在这里的应用就是:每个位置的左侧最大值等于它前一个的最大值跟它本身进行比较。右侧同理,所以是动态规划。
class Solution {
public int trap(int[] height) {
//有一种思路:可以计算出每个长方体上部的蓄水量。
//如何计算:可以求该处左侧最高长方体和右侧最高长方体,取最小值-该长方体高度
//如果取值为负那就是不蓄水,如果取值为正那该值就是它上面的蓄水量。
//重点是如何确定最大的位置;
int start=0,end=0;
int sumCount=0;
int []leftMax=new int[height.length];
int []rightMax=new int[height.length];
if(height.length==0){
return 0;
}
int leftmax=height[0];
int rightmax=height[height.length-1];
for(int i=height.length-1;i>=0;i--){
if(i==height.length-1){
rightMax[i]=height[i];
}
else{
if(rightmax<height[i]){
rightmax=height[i];
}
rightMax[i]=rightmax;
}
}
for(int i=0;i<height.length;i++){
if(i==0){
leftmax=height[i];
}
else{
if(leftmax<height[i]){
leftmax=height[i];
}
}
int min=Math.min(leftmax,rightMax[i]);
if((min-height[i])>0){
sumCount+=min-height[i];
}
}
return sumCount;
}
}