第十八天:力扣第845题,数组中的最长山脉
地址:leetcode-cn.com/problems/lo…
思路:这题不难只要能找到思路就非常简单,最长山脉就是比较,怎么去找山脉呢,先找山顶,通过山顶往两边遍历即可。
var longestMountain = function(A) {
let res = 0;
for(let i = 1; i < A.length - 1;i++)
{
if(A[i] > A[i-1]&&A[i] > A[i+1])//找山顶
{
let num = 1;
let n = i;
while(n > 0&&A[n] > A[n-1]){
num++;
n--;
}
let m = i;
while(m < A.length - 1&&A[m] > A[m+1])
{
num++;
m++;
}
if(num > res)
{
res = num ;
}
}
}
return res ;
};
执行用时:80 ms, 在所有 JavaScript 提交中击败了97.56%的用户
内存消耗:40.4 MB, 在所有 JavaScript 提交中击败了26.83%的用户
但其实还有一种枚举山脚的方法,可以使得空间复杂度减少。