python - 为什么这两段代码有不同的复杂度?
问题描述
这两段代码都做同样的事情,即检查列表中的单词magazine_words
是否足以构成列表中单词所指示的消息note_words
。然而,第一段代码需要更多的时间来执行,这不会让它在大输入时运行。这是为什么?由于两种解决方案都使用单个 for 循环,它们不应该具有相同的复杂性,即运行时间大致相同吗?
第一个解决方案:
lengths = input().split ()
m = int(lengths[0])
n = int(lengths [1])
magazine_words = input ().split()
note_words = input ().split()
def checkMagazine(m,n,magazine_words,note_words):
flag = "Yes"
for ind in range (n):
if not (note_words[ind] in magazine_words):
flag = "No"
break
else:
magazine_words.remove(note_words[ind])
return flag
print (checkMagazine(m,n,magazine_words,note_words))
第二种解决方案:
def ransom_note(magazine, ransom):
rc = {} # dict of word: count of that word in the note
for word in ransom:
if word not in rc:
rc[word] = 0
rc[word] += 1
for word in magazine:
if word in rc:
rc[word] -= 1
if rc[word] == 0:
del rc[word]
if not rc:
return True
return False
m, n = map(int, input().strip().split(' '))
magazine = input().strip().split(' ')
ransom = input().strip().split(' ')
answer = ransom_note(magazine, ransom)
if(answer):
print("Yes")
else:
print("No")```
解决方案
magazine_words.remove(note_words[ind])
秘密地是另一个循环-每次调用它时,它都必须遍历所有magazine_words
直到找到。note_words[ind]
推荐阅读
- c++ - 如何将文字转义转换为“真实”转义,以便“正确”打印它们?
- r - 使用分类数据而不是连接线创建线图
- javascript - 如何从祖先覆盖嵌套 Material UI 组件的样式?
- apache-kafka - 如何连接到内部 Kafka 集群
- r - 如何在 Rselenium R 中捕获动态 xpath id
- php - LeagueCSV:getRecords() 上的未定义索引
- pthreads - 在 C 中使用 pthread_mutex 同步分叉进程
- javascript - 未调用 jsgrid 控制器 updateItem
- excel - 从一个工作簿复制随机数据并将其粘贴到另一工作簿的同一行但不同列中
- c++ - 如何将对象的构造限制为几种方法?