代码随想录——最长连续递增序列(Leetcode 674)

题目链接
在这里插入图片描述

我的解法(暴力)

思路:
遍历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;
    }
}
  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值