【算法刷题day52】Leetcode:300. 最长递增子序列、674. 最长连续递增序列、718. 最长重复子数组

文章目录

草稿图网站
java的Deque

Leetcode 300. 最长递增子序列

题目: 300. 最长递增子序列
解析: 代码随想录解析

解题思路

dp数组的含义是以该元素为结尾的最大长度是多少,并使max来记录答案

代码

java 复制代码
class Solution {
    public int lengthOfLIS(int[] nums) {
        int n = nums.length;
        int []dp = new int[n];
        int max = 1;
        Arrays.fill(dp, 1);
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i])
                    dp[i] = Math.max(dp[i], dp[j] + 1);
            }
            max = Math.max(dp[i], max);
        }
        return max;
    }
}

总结

暂无

Leetcode 674. 最长连续递增序列

题目: 674. 最长连续递增序列
解析: 代码随想录解析

解题思路

和第300题的区别是,每次只要判断与前一个的对比

代码

java 复制代码
class Solution {
    public int findLengthOfLCIS(int[] nums) {
        int n = nums.length;
        int []dp = new int[n];
        int max = 1;
        Arrays.fill(dp, 1);
        for (int i = 1; i < n; i++) {
            if (nums[i-1] < nums[i])
                dp[i] = Math.max(dp[i], dp[i-1] + 1);
            max = Math.max(dp[i], max);
        }
        return max;
    }
}

总结

暂无

Leetcode 718. 最长重复子数组

题目: 718. 最长重复子数组
解析: 代码随想录解析

解题思路

使用二维数组,如果nums1的第i-1个元素和第nums2的第i-2个元素如果相同,则使匹配数dp[i][j]等于dp[i-1][j-1] + 1

代码

java 复制代码
class Solution {
    public int findLength(int[] nums1, int[] nums2) {
        int result = 0;
        int [][]dp = new int[nums1.length+1][nums2.length+1];
        for (int i = 1; i <= nums1.length; i++) {
            for (int j = 1; j <= nums2.length; j++) {
                if (nums1[i-1] == nums2[j-1])
                    dp[i][j] = dp[i-1][j-1] + 1;
                result = Math.max(result, dp[i][j]);
            }
        }
        return result;
    }
}

//滚动数组
class Solution {
    public int findLength(int[] nums1, int[] nums2) {
        int result = 0;
        int []dp = new int[nums2.length+1];
        for (int i = 1; i <= nums1.length; i++) {
            for (int j = nums2.length; j > 0; j--) {
                if (nums1[i-1] == nums2[j-1])
                    dp[j] = dp[j-1] + 1;
                else
                    dp[j] = 0;
                result = Math.max(result, dp[j]);
            }
        }
        return result;
    }
}

总结

暂无

相关推荐
故事和你914 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__4 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__5 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒6 小时前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣6 小时前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮6 小时前
Opus 4.7 来了,我并不建议你升级
算法
无敌昊哥战神7 小时前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__7 小时前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode