• 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)
  • 相关阅读:
    依赖倒置原则
    接口声明
    java泛型
    RandomAccessFile
    InputStreamReader/OutputStreamWriter乱码问题解决
    InputStreamReader和OutputStreamWriter
    Android开发UI之Notification
    Android开发UI之Toast的使用
    Android开发之PagerAdapter
    Android开发UI之ViewPager及PagerAdapter
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9932037.html
Copyright © 2020-2023  润新知