Trapping Rain Water & Container With Most Water & Product of Arrary 的解题在于使用双指针和保存最值
Trapping Rain Water
class Solution {
public int trap(int[] height) {
int len=height.length;
int res=0;
if(len<=2)
return res;
int left=0,right=len-1,maxleft=height[0],maxright=height[len-1];
while(left<right){
if(maxleft<maxright){
left++;
maxleft=Math.max(height[left],maxleft);
res+=maxleft-height[left];
}else{
right--;
maxright=Math.max(height[right],maxright);
res+=maxright-height[right];
}
}
return res;
}
}
Container With Most Water
class Solution {
public int maxArea(int[] height) {
int maxwater=0,len=height.length;
if(len<2)
return maxwater;
int left=0,right=len-1;
while(left<right){
if(height[left]<height[right]){
maxwater=Math.max(maxwater,height[left]*(right-left));
left++;
}else{
maxwater=Math.max(maxwater,height[right]*(right-left));
right--;
}
}
return maxwater;
}
}
Product of Arrary
class Solution {
public int[] productExceptSelf(int[] nums) {
int res[]=new int[nums.length];
Arrays.fill(res,1);
for(int i=1;i<nums.length;i++)
res[i]=res[i-1]*nums[i-1];
int right=1;
for(int i=nums.length-2;i>=0;i--){
right*=nums[i+1];
res[i]*=right;
}
return res;
}
}
Trapping Rain Water II
这道题目比较不好想,所以需要列出来一个二维数组实际的走一遍,其次是每次更新压入队列中的数值有一定的道理和逻辑。
class Solution {
public int trapRainWater(int[][] heightMap) {
PriorityQueue<int[]> queue=new PriorityQueue<int[]>(new Comparator<int[]>(){
public int compare(int pos1[],int pos2[]){
return pos1[2]-pos2[2];
}
});
int m=heightMap.length,maxwater=0;
if(m<=2)
return maxwater;
int n=heightMap[0].length;
boolean visit[][]=new boolean[m][n];
for(int i=0;i<m;i++){
queue.offer(new int[]{i,0,heightMap[i][0]});
visit[i][0]=true;
queue.offer(new int[]{i,n-1,heightMap[i][n-1]});
visit[i][n-1]=true;
}
for(int i=1;i<n-1;i++){
queue.offer(new int[]{0,i,heightMap[0][i]});
visit[0][i]=true;
queue.offer(new int[]{m-1,i,heightMap[m-1][i]});
visit[m-1][i]=true;
}
int d[][]=new int[][]{{0,1},{1,0},{-1,0},{0,-1}};
while(!queue.isEmpty()){
int temp[]=queue.poll();
for(int i=0;i<d.length;i++){
int x=temp[0]+d[i][0];
int y=temp[1]+d[i][1];
if(x>=0 && x<m && y>=0 && y<n && !visit[x][y]){
visit[x][y]=true;
if(heightMap[x][y]>=temp[2]){
queue.offer(new int[]{x,y,heightMap[x][y]});
}else{
maxwater+=temp[2]-heightMap[x][y];
queue.offer(new int[]{x,y,temp[2]});
}
}
}
}
return maxwater;
}
}