这两段代码的作用是相同的,它们检查列表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]
相关问题 更多 >
编程相关推荐