leetcode day 8【 822. 翻转卡片游戏】从暴力到哈希

leetcode day 8【 822. 翻转卡片游戏】从暴力到哈希,第1张

leetcode day 8【 822. 翻转卡片游戏】从暴力到哈希

解题思路 暴力
class Solution:
    def flipgame(self, fronts: List[int], backs: List[int]) -> int:
        minnum = 0
        samelist = []
        for i in range(len(fronts)):
            if fronts[i] == backs[i]:
                samelist.append(fronts[i])
        for i in range(len(fronts)):
            if fronts[i] not in samelist and (minnum == 0 or fronts[i] < minnum):
                minnum = fronts[i]
            if backs[i] not in samelist and (minnum == 0 or backs[i] < minnum):
                minnum = backs[i]
        return minnum

引入哈希

用哈希代替重复列表

  • set:
class Solution:
    def flipgame(self, fronts: List[int], backs: List[int]) -> int:
        minnum = 2001
        sameset = set()
        for i in range(len(fronts)):
            if fronts[i] == backs[i]:
                sameset.add(fronts[i])
        for ele in fronts+backs:
            if ele not in sameset:
                minnum = min(ele, minnum)
        return minnum if minnum != 2001 else 0

  • dict:
class Solution:
    def flipgame(self, fronts: List[int], backs: List[int]) -> int:
        minnum = 2001
        same = {fronts[i] for i in range(len(fronts)) if fronts[i] == backs[i]}
        for ele in fronts+backs:
            if ele not in same:
                minnum = min(ele, minnum)
        return minnum if minnum != 2001 else 0

总结:
python中的set是一个无重复的集合。
python中的hash可以用字典来实现,字典的更新可以直接用dict[…] = ……更新,其中,key可以是非字符串。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5480097.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存