给定一个
未经排序
的整数数组,找到最长且连续
的递增序列,并返回该序列的长度
。
示例 1:
输入: [1,3,5,4,7]
输出: 3
解释: 最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。
示例 2:
输入: [2,2,2,2,2]
输出: 1
解释: 最长连续递增序列是 [2], 长度为1。
注意: 数组长度不会超过10000。
思路: 连续递增,那么只考虑nums[i]
和其前面的nums[i-1]
即可
解法一:
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;
}
}
时间复杂度:O(n)
空间压缩:O(n)
解法二:滑动窗口(状态压缩),只需要保存前面的状态即可,而不需要保存所有状态
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;
}
}
时间复杂度:O(n)
空间压缩:O(1)