我的解法(暴力)
思路:
遍历nums数组,如果存在连续递增则记录,不存在连续则跳出遍历
class Solution {
public int findLengthOfLCIS(int[] nums) {
int res = 1;
for(int i = 0; i < nums.length - 1; i++){
int count = 1;
for(int j = i + 1; j < nums.length; j++){
if(nums[j] > nums[j - 1]){
count++;
res = Math.max(res, count);
}else{
break;
}
}
}
return res;
}
}
优秀解法(贪心)
思路同上
class Solution {
public int findLengthOfLCIS(int[] nums) {
int res = 1;
int count = 1;
for(int i = 1; i < nums.length; i++){
if (nums[i] > nums[i - 1]) {
count++;
} else {
count = 1;
}
if (count > res) res = count;
}
return res;
}
}
优秀解法(动态规划)
思路:
-
确定dp数组(dp table)以及下标的含义
dp[i]:以下标i为结尾的连续递增的子序列长度为dp[i]。 -
确定递推公式
如果 nums[i] > nums[i - 1],那么以 i 为结尾的连续递增的子序列长度 一定等于 以i - 1为结尾的连续递增的子序列长度 + 1 。
dp[i] = dp[i - 1] + 1;
注意这里就体现出和动态规划:300.最长递增子序列 (opens new window)的区别!
本题要求连续递增子序列,所以就只要比较nums[i]与nums[i - 1],而不用去比较nums[j]与nums[i](j是在0到i之间遍历)。
既然不用j了,那么也不用两层for循环,本题一层for循环就行,比较nums[i] 和 nums[i - 1]。
-
dp数组如何初始化
以下标i为结尾的连续递增的子序列长度最少也应该是1,即就是nums[i]这一个元素。
所以dp[i]应该初始1;
-
确定遍历顺序
从递推公式上可以看出, dp[i + 1]依赖dp[i],所以一定是从前向后遍历。
class Solution {
public int findLengthOfLCIS(int[] nums) {
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
int res = 1;
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] > nums[i]) {
dp[i + 1] = dp[i] + 1;
}
res = res > dp[i + 1] ? res : dp[i + 1];
}
return res;
}
}