LeetCode 718. 最长重复子数组

news/2024/5/20 8:06:17 标签: 滑动窗口

原题目:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/

 

思路:

滑动窗口

代码:

class Solution {
public:
    int maxLength(vector<int>& A, vector<int>& B, int addA, int addB, int len) {
        int ret = 0, k = 0;
        for (int i = 0; i < len; i++) {
            if (A[addA + i] == B[addB + i]) {
                k++;
            } else {
                k = 0;
            }
            ret = max(ret, k);
        }
        return ret;
    }
    int findLength(vector<int>& A, vector<int>& B) {
        int n = A.size(), m = B.size();
        int ret = 0;
        for (int i = 0; i < n; i++) {
            int len = min(m, n - i);
            int maxlen = maxLength(A, B, i, 0, len);
            ret = max(ret, maxlen);
        }
        for (int i = 0; i < m; i++) {
            int len = min(n, m - i);
            int maxlen = maxLength(A, B, 0, i, len);
            ret = max(ret, maxlen);
        }
        return ret;
    }
};

 


http://www.niftyadmin.cn/n/899038.html

相关文章

LeetCode 122. 买卖股票的最佳时机 II

原题目&#xff1a;https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/ 思路&#xff1a; 扫描数组&#xff0c;如果今天的而价格比昨天的高&#xff0c;就卖出 代码&#xff1a; class Solution { public:int maxProfit(vector<int>& prices)…

LeetCode 378. 有序矩阵中第K小的元素

原题目&#xff1a;https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/ 思路一&#xff1a; 使用大顶堆&#xff0c;找出前k小。 代码&#xff1a; class Solution { public:int kthSmallest(vector<vector<int>>& matrix, int k) …

LeetCode 455. 分发饼干

原题目&#xff1a;https://leetcode-cn.com/problems/assign-cookies/ 思路&#xff1a; 对数组进行排序&#xff0c;然后使用贪心法即可&#xff0c;找到可以给孩子的饼干就给他。 如果s[j] > g[i] i。 代码&#xff1a; class Solution { public:int findContentChild…

LeetCode 134. 加油站

原题目&#xff1a;https://leetcode-cn.com/problems/gas-station/ 思路&#xff1a; 如果可以绕行一圈&#xff0c;那么需要满足两个条件 1、车子可以从i开到i1&#xff0c;即车子开到i1使得油tmp≥0 2、全程油的量要大于耗费的量 sum ≥ cost 实现&#xff1a; 用ai表示…

LeetCode 860. Lemonade Change

原题目&#xff1a;https://leetcode-cn.com/problems/lemonade-change/ 思路&#xff1a; 因为只有5/10/20三种情况&#xff0c;我们可以对三种情况分别进行判断。 我们使用five和ten记录5块和10块的张数&#xff0c;用于找零钱 代码&#xff1a; class Solution { public:…

LeetCode 435. Non-overlapping Intervals

原题目&#xff1a;https://leetcode-cn.com/problems/non-overlapping-intervals/ 思路&#xff1a; 首先根据起点对数据进行排序&#xff0c;分析可知&#xff0c;会出现两种情况 1、后一个的起点大于等于前一个的重点&#xff0c;此时不需要删除节点&#xff0c;用left记住…

LeetCode 44. Wildcard Matching

原题目&#xff1a;https://leetcode-cn.com/problems/wildcard-matching/ 思路&#xff1a; 本题可以使用动态规划的思想求解&#xff0c;动态规划有两个步骤&#xff1a;找出转移方程&#xff0c;确定初始&#xff08;边界&#xff09;条件 我们使用dp[i][j]来表示s中前i个…

LeetCode 874. Walking Robot Simulation

原题目&#xff1a;https://leetcode-cn.com/problems/walking-robot-simulation/ 思路&#xff1a; 用0,1,2,3模拟走的方向&#xff0c;分别代表北东南西&#xff0c;用map存储障碍的位置&#xff0c;每次移步之前&#xff0c;先判断下一步是不是障碍&#xff0c;如果是就不在…