zoukankan      html  css  js  c++  java
  • 718. Maximum Length of Repeated Subarray

    Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

    Example 1:

    Input:
    A: [1,2,3,2,1]
    B: [3,2,1,4,7]
    Output: 3
    Explanation: 
    The repeated subarray with maximum length is [3, 2, 1].
    

    Note:

    1. 1 <= len(A), len(B) <= 1000
    2. 0 <= A[i], B[i] < 100

    Approach #1: Dynamic programming

    class Solution {
    public:
        int findLength(vector<int>& A, vector<int>& B) {
            int ans = 0;
            int lenA = A.size();
            int lenB = B.size();
            vector<vector<int>> memo(lenA+1, vector<int>(lenB+1, 0));
            for (int i = lenA-1; i >= 0; --i) {
                for (int j = lenB-1; j >= 0; --j) {
                    if (A[i] == B[j]) {
                        memo[i][j] = memo[i+1][j+1] + 1;
                        ans = max(ans, memo[i][j]);
                    }
                }
            }
            return ans;
        }
    };
    

    Runtime: 92 ms, faster than 65.15% of C++ online submissions for Maximum Length of Repeated Subarray.

    Analysis:

    maybe using dynamic programming from back to front is the key to solve these similar questions.

    there are some other ways to solve this problem.

    https://leetcode.com/problems/maximum-length-of-repeated-subarray/

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    python命名
    类的绑定方法与非绑定方法
    类的封装
    类的多态性
    python中的while循环和for循环
    python的单、双、多分支流程控制
    python中的运算符
    python中的变量
    接口与归一化设计
    类的继承
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9932037.html
Copyright © 2011-2022 走看看