博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
718. Maximum Length of Repeated Subarray(python+cpp)
阅读量:3704 次
发布时间:2019-05-21

本文共 1851 字,大约阅读时间需要 6 分钟。

题目:

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

解释:

LCS最长公共子序列,注意是subarray,不是subsequence
1.dp[i][j]表示以A[i-1](A的第i个元素)和B[j-1](B的第j个元素)结尾的)的最长repeated subarray(这两个元素一定要存在在repeated subarray中)
那么转移方程为

if A[i]==B[j]: 		dp[i][j]=dp[i-1][j-1]+1	else:		dp[i][j]=0	return maxLen

2.如果是subsequence, dp[i][j] 表示A的前i个元素和B的前j个元素构成的子序列所组成的LCS,那么转移方程是

dp[i][0]=0,dp[0][j]=0	if A[i]==B[j]:		dp[i][j]=dp[i-1][j-1]+1	else:		dp[i][j]=max(dp[i-1][j],dp[i][j-1])	#需要注意这里	return dp[m][n]

可是这种解法速度好慢啊,居然要5000ms????

python代码:

class Solution:    def findLength(self, A, B):        """        :type A: List[int]        :type B: List[int]        :rtype: int        """        m=len(A)        n=len(B)        dp=[[0]*(n+1) for _ in range(m+1)]        maxLen=0        for i in range(1,m+1):            for j in range(1,n+1):                if A[i-1]==B[j-1]:                    dp[i][j]=dp[i-1][j-1]+1                    maxLen=max(maxLen,dp[i][j])                else:                    dp[i][j]=0        return maxLen

c++代码:

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

总结:

需要注意是subarray 还是subsequence。

转载地址:http://iwmcn.baihongyu.com/

你可能感兴趣的文章
css隐藏自带的滚动轴,兼容IE,FF,Webkit 和 O
查看>>
form表单提交的几种方式
查看>>
canvas实现在线签名
查看>>
'NoneType' object has no attribute 'configure'
查看>>
Django创建应用
查看>>
Django管理站点操作
查看>>
MySQL5.5升级5.7--net start mysql发生系统错误3。系统找不到指定的路径。
查看>>
使用redis的increment()方法实现计数器功能
查看>>
MySQL(一)存储引擎
查看>>
MySQL(二)锁机制【表级锁、页面锁、行级锁】
查看>>
推荐一款实用的java工具包---Hutool
查看>>
使用阿里的EasyExcel实现表格导出功能
查看>>
ActiveMQ主从集群
查看>>
RabbitMQ基础概念详解
查看>>
解析三种常见分布式锁的实现
查看>>
并发、并行、串行概念
查看>>
学习多线程——必会的的9个方法
查看>>
线程的生命周期
查看>>
SpringBoot项目实现多文件上传
查看>>
SpringBoot整合Thymeleaf
查看>>