用的是双指针法:
定义两个指针left和right,从左右两边开始遍历,没移动一次就将两个指针对应位置的高度进行比较:在高度较低的一边进行加水。此时需要注意当前高度和当前部分的最大高度之间的差值就是接水的数量。然后让指针向中间移动。
这个方法很巧妙,如果想明白了,比用其他方法简单。
代码class Solution {
public int trap(int[] height) {
int left = 0;
int right = height.length-1;
int leftMax = 0;
int rightMax = 0;
int res = 0;
while(leftheight[left]?leftMax:height[left];
res += leftMax - height[left];
left++;
}else{
rightMax = rightMax>height[right]?rightMax:height[right];
res += rightMax-height[right];
right--;
}
}
return res;
}
}
LeetCode48. 旋转图像
思路
先沿对称轴反转然后再要中线反转即可。
代码class Solution {
public void rotate(int[][] matrix) {
int temp = 0;
for(int i =0;i



