analysis - 我怎样才能使用贪婪获得 O(m+n) ?
问题描述
我如何O(m+n)
为这种情况设计一个贪心算法
给定两种安排L1
and L2
, where| L1 | = n
和| L2 | = m
.
L2
据说是L1
if 元素可以从L1
to get中删除的子序列L2
。这意味着对于m
每个. 设计一个贪心算法,检测是否是 的子序列,如果是 的子序列,则输出索引。ik∈ [0..n]
L1 [ik] = L2 [j]
j∈ [0..m]
O (n + m)
L2
L1
ik
L1
L2
L1
例子:
Input L1 = [1 2 3 4 5 6 7 8 9 10] L2 = [3 5 7 9] Output ik = [2 4 6 8]
Input L1 = [2 1 4 3 6 5 7 8 9 10] L2 = [1 6 5 10] Output ik = [1 4 5 9]
Input L1 = [1 2 3 4 5 6 7 8 9 10] L2 = [1 5 9 12] Output L2 is not subsequence of L1
我一直在用这个做经典代码
bool isSubsequence(string str1, string str2) {
int i=0;
int j=0;
while (j<str1.length() && i<str2.length()){
if(str1[j]==str2[i]){
cout<<i<<" ";
j++;
}
i++;
}
return j==str1.length();
}
但我不知道如何O(m+n)
使用贪婪。谢谢
解决方案
推荐阅读
- docker - 如何在 Windows 10 上通过 DockerNAT IP 地址访问 Docker 容器?
- git - Windows 中更改密码后:密码提示后 Git 身份验证失败
- sql-server - 如何在 SQL Server 中创建自定义年/周字段?
- c++ - 链接库 .a 和库 .lib
- c# - Authorize 和 AllowAnonymous 元数据在应用于控制器时给出不同的行为
- amazon-web-services - 如何使用 AWS Cloudformer 为现有 API Gateway 创建云形成模板?
- mongodb - 如何从数组中获取从索引到末尾的元素
- etl - 简单的“读取文件 > 创建哈希文件作业”中的 mkdbfile 问题
- android - 如何获取不同波特率的事件?
- php - 如何使用 dompdf 或任何其他库生成 pdf,其中 html 和 php 一起编写?