LeetCode#718 Maximum Length of Repeated Subarray (week9)
2017-10-31 18:19
477 查看
week9
题目
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
原题地址:https://leetcode.com/problems/maximum-length-of-repeated-subarray/description/
解析
题目要求找到两个数组相同的最长子数组并返回其长度。大致思路是用两重循环,外循环指定第一个数组的位置,内循环指定第二个数组的位置,以这两个位置分别为两个子数组的起始位置,检索直至相对应的某一位元素不同,得到以这两个位置为起始的最长相同子数组长度。
注意到上述做法可以找到正确答案,但是中间却做了很多不必要的工作,考虑数组[1,2,3,4,1]和[2,1,2,3,4],按照循环会找到[1,2,3,4]和[1,2,3,4],也会找到[2,3,4]和[2,3,4],但可以发现后者是前者一部分,因此检索时可直接跳过,跳过的条件是起始位置均在前者(已经找到的最长相同子数组)的中间,以此节省检索时间。
代码
class Solution { public: int findLength(vector<int>& A, vector<int>& B) { int max = 0; /*记录已知最长相同子数组在两个原数组中的起始位置和结束位置*/ int A_s = 0, A_e = 0, B_s = 0, B_e = 0; for (int i = 0; i < A.size(); ++i) { for (int j = 0; j < B.size(); ++j) { int k = 0; bool breakFlag = false; if (!(i > A_s && i <= A_e && j > B_s && j <= B_e)) { while (A[i + k] == B[j + k]) { if ((i + k + 1) < A.size() && (j + k + 1) < B.size()) { ++k; } else { /*如果是因为检索到数组末尾跳出循环,k为当前最长相同子数组长度-1*/ breakFlag = true; break; } } int current = breakFlag ? (++k) : k; if (current > max) { max = current; A_s = i; A_e = i + current - 1 ; B_s = j; B_e = j + current - 1; } } } } return max; } };
相关文章推荐
- Maximum Length of Repeated Subarray
- LeetCode 718 Maximum Length of Repeated Subarray
- LeetCode #718 Maximum Length of Repeated Subarray
- Maximum Length of Repeated Subarray问题及解法
- LeetCode-718:Maximum Length of Repeated Subarray (最长公共子数组) -- medium
- LeetCode:Maximum Length of Repeated Subarray
- Leetcode 718 Maximum Length of Repeated Subarray
- Maximum Length of Repeated Subarray
- 第16周Maximum Length of Repeated Subarray
- leetcode练习 Maximum Length of Repeated Subarray
- 算法题目--Maximum Length of Repeated Subarray
- Maximum Length of Repeated Subarray解题报告
- HashTable-718-Maximum Length of Repeated Subarray
- Maximum Length of Repeated Subarray
- Array-Maximum Length of Repeated Subarray
- leetcode: Maximum Length of Repeated Subarray
- LeetCode算法问题11 —— Maximum Length of Repeated Subarray
- Leetcode | Maximum Length of Repeated Subarray
- LeetCode.718 Maximum Length of Repeated Subarray(经典DP问题)
- [leetcode]Maximum Length of Repeated Subarray