LeetCode 10.25每日一题845. 数组中的最长山脉:https://leetcode-cn.com/problems/longest-mountain-in-array/
思路:根据前后数的大小及山脉的状态(上升还是下降),分情况判断,简单粗暴。官方思路,枚举山顶和山脚(动态规划)。
完整代码:
/** * @param {number[]} A * @return {number} */ var longestMountain = function(A) { var isup = true; var len = 0; var maxlen = 0; var stack = [A[0]]; for (var i = 0; i < A.length - 1; i++) { if (A[i + 1] < A[i]) { //后数比前数要小 if (isup) { //上升阶段 if (stack.length >= 2) { //已形成山脉,转下降阶段 isup = false; stack.push(A[i + 1]); len = stack.length >= 3 ? stack.length : 0; maxlen = len > maxlen ? len : maxlen; } else { //还未形成山脉,清空数组,另起山脉 stack = []; stack.push(A[i + 1]); } } else { //下降阶段,直接push进数组 stack.push(A[i + 1]); len = stack.length >= 3 ? stack.length : 0; maxlen = len > maxlen ? len : maxlen; } } else if (A[i + 1] ==A[i]) { //两数相等,另起山脉 if(!isup){ len = stack.length >= 3 ? stack.length : 0; maxlen = len > maxlen ? len : maxlen; } isup = true; stack = []; stack.push(A[i + 1]); } else { //后数比前数大 if (isup) { //上升阶段则直接push进数组 stack.push((A[i + 1])); } else { //下降阶段则另起山脉 len = stack.length >= 3 ? stack.length : 0; maxlen = len > maxlen ? len : maxlen; isup = true; stack = []; stack.push(A[i]); stack.push(A[i + 1]); } } } return maxlen; };
执行结果:
找山顶解法,这种解法思路也非常巧妙。
作者:a-mao-da-ma 链接:https://leetcode-cn.com/problems/longest-mountain-in-array/solution/shu-zu-zhong-de-zui-chang-shan-mai-by-a-mao-da-ma/
来源:leedcode
/** * @param {number[]} A * @return {number} */ 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 len = i let count = 1 while(A[len] > A[len-1] && len > 0) { count++ len-- } len = i while(A[len] > A[len+1] && len < A.length) { count++ len++ } res = res > count ? res : count } } return res };