java两种方法形象题解,爬山、下山,直接找山顶!击败99%!
先爬山,再下山
遍历 A A A数组, c o u n t count count记录当前山脉的长度,默认从1开始,山脉必须满足的条件是先上山,再下山:
- 如果 A [ i ] > A [ i − 1 ] A[i] > A[i - 1] A[i]>A[i−1]说明现在处于爬山阶段 c o u n t + + count++ count++。
- 如果 A [ i ] < A [ i − 1 ] A[i] < A[i - 1] A[i]<A[i−1]并且 c o u n t ! = 1 count != 1 count!=1说明现在处于下山阶段( c o u n t ! = 1 count != 1 count!=1保证前面上过山,不能直接下山),此时只能继续下山(如果又上山就是另一座山了),因此使用 w h i l e while while循环一直到不能继续下山为止,记录此时最长的长度。之后重置 c o u n t count count值,这时有一点需要注意,如果当前值比之前值大的话可以作为已经开始上了一层山了,因此 c o u n t count count的值应该为2。
class Solution {
public int longestMountain(int[] A) {
if(A.length == 0) return 0;
int count = 1, max = 0;
for (int i = 1; i < A.length; i++) {
if (A[i] > A[i - 1]) count++;
else if(A[i] < A[i - 1] && count != 1) {
while(i < A.length && A[i] < A[i - 1]){
count++;
i++;
}
max = Math.max(max, count);
if(i < A.length){
if(A[i] > A[i - 1]) count = 2;
else count = 1;
}
}else count = 1;
}
// for(int i : dp) System.out.printf(i + " ");
return max;
}
}
时间复杂度
遍历一遍数组为 O ( n ) O(n) O(n)。
空间复杂度
使用常量级空间, O ( 1 ) O(1) O(1)。
找山顶
直接在 A A A数组中找满足 A [ i − 1 ] < A [ i ] > A [ i + 1 ] A[i - 1] < A[i] > A[i + 1] A[i−1]<A[i]>A[i+1]的山顶点,然后向左右两边遍历下山,统计左右两边长度 l e f t , r i g h t left, right left,right,然后记录最长的 l e f t + r i g h t + 1 left + right + 1 left+right+1的长度。
这里注意的点是,要跳过右边下山的阶段 i = j − 1 i = j - 1 i=j−1,因为下山一定不满足存在山顶的情况。
class Solution {
public int longestMountain(int[] A) {
//找山顶
int max = 0;
for (int i = 1; i < A.length - 1; i++) {
if (A[i] > A[i - 1] && A[i] > A[i + 1]){
int j;
int left = 0;
for(j = i - 1; j >= 0; j--) {
if (A[j] < A[j + 1]) left++;
else break;
}
int right = 0;
for (j = i + 1; j < A.length; j++) {
if (A[j] < A[j - 1]) right++;
else break;
}
max = Math.max(max, left + right + 1);
i = j - 1;
}
}
return max;
}
}
时间复杂度
遍历一遍数组(循环的部分跳过了), O ( n ) O(n) O(n)。
空间复杂度
常量级额外空间。