674. Secuencia creciente consecutiva más larga
Dada una
未经排序
matriz entera, encuentre la连续
secuencia más larga y creciente y devuelva esa secuencia长度
.
Ejemplo 1:
输入: [1,3,5,4,7]
输出: 3
解释: 最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。
Ejemplo 2:
输入: [2,2,2,2,2]
输出: 1
解释: 最长连续递增序列是 [2], 长度为1。
Nota: La longitud de la matriz no superará los 10.000.
Ideas: continuas hacia arriba, así que solo considera nums[i]
y su frente nums[i-1]
puede
Solución uno :
class Solution {
public int findLengthOfLCIS(int[] nums) {
int LEN = nums.length;
if(LEN == 0 || nums == null) return 0;
int[] dp = new int[LEN];
Arrays.fill(dp, 1);
int res = 0;
for(int i = 1; i < LEN; i++){
if(nums[i-1] < nums[i]){
dp[i] = dp[i-1]+1;
}
res = Math.max(res, dp[i]);
}
return (res > 1)? res:1;
}
}
Complejidad del tiempo: O (n)
Compresión de espacio: O (n)
Solución 2 : ventana deslizante (compresión de estado), solo es necesario guardar el estado anterior, no todos los estados
class Solution {
public int findLengthOfLCIS(int[] nums) {
int LEN = nums.length;
if(LEN == 0 || nums == null) return 0;
int pre = 1;
int cur = 1;
int res = 0;
for(int i = 1; i < LEN; i++){
pre = cur;
if(nums[i-1] < nums[i]){
cur = pre + 1;
}else{
cur = 1;
}
res = Math.max(res, cur);
}
return (res > 1)? res:1;
}
}
Complejidad del tiempo: O (n)
Compresión de espacio: O (1)