LeetCode题解系列--718. Maximum Length of Repeated Subarray
来源:互联网 发布:淘宝店lol代练哪家可靠 编辑:程序博客网 时间:2024/06/06 02:14
描述
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 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100
难度 : medium
思路
使用动态规划算法,首先需要找出做动态规划的状态,与状态转移方程。
至于怎么想到的,我也不知道,一开始一看到也不知道怎么做,突然就想到了。。
设C[i][j] 为以A[i] 和 B[j] 结尾的最长子串的长度,可以看出这种状态表示方法可以表示找出最长子串。
状态转移方程:
当A[i] 和 B[j] 相等时,以A[i - 1] 和 B[j - 1] 结束的子串可以增长1,若不想等,则此处最长子串长度为0 。
得出解答:
答案
class Solution {public: int findLength(vector<int>& A, vector<int>& B) { vector<vector<int> > C(A.size() + 1, vector<int>(B.size() + 1, 0)); int result = 0; for (int i = 1; i < A.size() + 1; ++i) { for (int j = 1; j < B.size() + 1; ++j) { if (A[i - 1] == B[j - 1]) { C[i][j] = C[i - 1][j - 1] + 1; } result = result > C[i][j] ? result : C[i][j]; } } return result; }};
优化
这种方法的空间复杂度比较高,有O(nm),仔细观察内层循环,我们可以发现对于一个外层循环其实只需要用到C的两行,第i行和第i-1行,所以C其实只需要是一个2*m的数组就可以了。
class Solution {public: int findLength(vector<int>& A, vector<int>& B) { vector<vector<int> > C(2, vector<int>(B.size() + 1, 0)); int result = 0; int first = 0; int second = 1; for (int i = 1; i < A.size() + 1; ++i) { for (int j = 1; j < B.size() + 1; ++j) { if (A[i - 1] == B[j - 1]) { C[second][j] = C[first][j - 1] + 1; } else { C[second][j] = 0; } result = result > C[second][j] ? result : C[second][j]; } swap(first, second); } return result; }};
这种方法的空间复杂度为O(n)
点击这里查看更多我的leetcode答案
阅读全文
1 0
- LeetCode题解系列--718. Maximum Length of Repeated Subarray
- Leetcode 718. Maximum Length of Repeated Subarray
- Leetcode 718. Maximum Length of Repeated Subarray
- leetcode 718. Maximum Length of Repeated Subarray
- [LeetCode]718. Maximum Length of Repeated Subarray
- [LeetCode] 718. Maximum Length of Repeated Subarray
- [leetcode] 718. Maximum Length of Repeated Subarray
- Leetcode:718. Maximum Length of Repeated Subarray
- leetcode 718( Maximum Length of Repeated Subarray)
- Leetcode | Maximum Length of Repeated Subarray
- LeetCode #718 Maximum Length of Repeated Subarray
- Leetcode | Maximum Length of Repeated Subarray
- LeetCode:Maximum Length of Repeated Subarray
- [leetcode]Maximum Length of Repeated Subarray
- [LeetCode]Maximum Length of Repeated Subarray
- Leetcode 718 Maximum Length of Repeated Subarray
- LeetCode:Maximum Length of Repeated Subarray
- leetCode-Maximum Length of Repeated Subarray
- Win10开启IPv6
- 20171101-程序员的自我修养
- Linux下PHP安装redis扩展
- C语言中用循环打印各种图形
- Linux系统基础(十二)
- LeetCode题解系列--718. Maximum Length of Repeated Subarray
- 删数问题(山东理工2072)
- 事件循环与任务队列
- xamarin学习笔记A16(安卓OkHttp3和HttpURLConnection)下
- java习题
- MySQL中给中文进行排序
- final修饰类和方法
- 滚动条
- 代理模式