mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-13 22:35:09 +08:00
Update 0718.最长重复子数组.md
This commit is contained in:
@ -198,7 +198,57 @@ public:
|
|||||||
|
|
||||||
而且为了让 `if (dp[i][j] > result) result = dp[i][j];` 收集到全部结果,两层for训练一定从0开始遍历,这样需要加上 `&& i > 0 && j > 0`的判断。
|
而且为了让 `if (dp[i][j] > result) result = dp[i][j];` 收集到全部结果,两层for训练一定从0开始遍历,这样需要加上 `&& i > 0 && j > 0`的判断。
|
||||||
|
|
||||||
相对于版本一来说还是多写了不少代码。而且逻辑上也复杂了一些。 优势就是dp数组的定义,更直观一点。
|
对于基础不牢的小白来说,在推导出转移方程后可能疑惑上述代码为什么要从`i=0,j=0`遍历而不是从`i=1,j=1`开始遍历,原因在于这里如果不是从`i=0,j=0`位置开始遍历,会漏掉如下样例结果:
|
||||||
|
```txt
|
||||||
|
nums1 = [70,39,25,40,7]
|
||||||
|
nums2 = [52,20,67,5,31]
|
||||||
|
```
|
||||||
|
|
||||||
|
当然,如果你愿意也可以使用如下代码,与上面那个c++是同一思路:
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
public int findLength(int[] nums1, int[] nums2) {
|
||||||
|
int len1 = nums1.length;
|
||||||
|
int len2 = nums2.length;
|
||||||
|
int[][] result = new int[len1][len2];
|
||||||
|
|
||||||
|
int maxresult = Integer.MIN_VALUE;
|
||||||
|
|
||||||
|
for(int i=0;i<len1;i++){
|
||||||
|
if(nums1[i] == nums2[0])
|
||||||
|
result[i][0] = 1;
|
||||||
|
if(maxresult<result[i][0])
|
||||||
|
maxresult = result[i][0];
|
||||||
|
}
|
||||||
|
|
||||||
|
for(int j=0;j<len2;j++){
|
||||||
|
if(nums1[0] == nums2[j])
|
||||||
|
result[0][j] = 1;
|
||||||
|
if(maxresult<result[0][j])
|
||||||
|
maxresult = result[0][j];
|
||||||
|
}
|
||||||
|
|
||||||
|
for(int i=1;i<len1;i++){
|
||||||
|
for(int j=1;j<len2;j++){
|
||||||
|
|
||||||
|
if(nums1[i]==nums2[j])
|
||||||
|
result[i][j] = result[i-1][j-1]+1;
|
||||||
|
|
||||||
|
if(maxresult<result[i][j])
|
||||||
|
maxresult = result[i][j];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return maxresult;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
对于小白来说一定要明确dp数组中初始化的数据是什么
|
||||||
|
|
||||||
|
整体而言相对于版本一来说还是多写了不少代码。而且逻辑上也复杂了一些。 优势就是dp数组的定义,更直观一点。
|
||||||
|
|
||||||
## 其他语言版本
|
## 其他语言版本
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user