第一题 盛最多水的容器 leetcode传送门
思路:双指针
(1)一个在开始位置,一个为末尾位置
(2) 双指针重合结束终止
(3) 计算当前的容量
temp = (right - left) * Math.min( arr[right], arr.[left] )
(4) 与当前的最大值相比
maxTemp = Math.max (maxTemp,temp)
(5)指针的挪动,那边当前的值小,就挪动那边
var maxArea = function(height) {
let left = 0;
let right = height.length - 1
let maxTemp = 0
while(left<right){
let temp = (right-left) * Math.min(height[left],height[right])
maxTemp = Math.max(maxTemp,temp)
if(height[left]<height[right]){
left++
}else{
right--
}
}
return maxTemp
}
第二题 接雨水 leetcode传送门
思路一:
(1)找到最高点,将数组分为两部分,最高点的左半部分和右半部分
(2)对于左半部分,每个位置的盛水量就是该位置与[0-当前位置]中的左边最高点之间的差
(3)对于左半部分,每个位置的盛水量就是该位置与[末尾到-当前位置]中的右边最高点之间的差
/**
* @param {number[]} height
* @return {number}
*/
function(height) {
let MaxTemp = 0
let maxIndex = 0
let res = 0
//找到最大值及其索引
for(let i=0;i<height.length;i++){
if(height[i] > MaxTemp) {
MaxTemp = height[i]
maxIndex = i
}
}
// 左半部分
for(let i = 0;i<maxIndex;i++){
for(let j=i+1;j<=maxIndex;j++){
if(height[i]>height[j]){
res = res + height[i]-height[j]
}else {
i = j
}
}
}
// 右半部分
for(let i = height.length-1;i>maxIndex;i--){
for(let j = i-1;j>=maxIndex;j--){
if(height[i]>height[j]){
res = res + height[i] - height[j]
}else{
i = j
}
}
}
return res
}
思路二:双指针 (1)确定双指针的位置,一个在起始位置,一个在末尾
(2)letftmax来记录当前左边的最高点,right来记录当前右边的最高点
(3)双指针重合结束终止
(4)指针的挪动原则: 当height[left] < height[right]时候,这时候一定有 leftmax < rightMax ,此时挪动left++,相反时,这意味left在maxleft处等待right挪过来,此时right--.
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
let left = 0
let right = height.length-1
let leftMax = 0
let rightMax = 0
let res = 0
while(left < right){
if(height[left] < height[right]){
if(height[left] > leftMax){
leftMax = height[left]
}
res = res + leftMax - height[left]
left++
}else{
if(height[right]>rightMax){
rightMax = height[right]
}
res = res + rightMax - height[right]
right --
}
}
return res
};