为什么这两段代码具有不同的复杂性?

2024-09-28 01:26:00 发布

您现在位置: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")```

Tags: inforinputif解决方案wordintnote

热门问题