leetcode 141. 环形链表 67. 二进制求和 299. 猜数字游戏

    科技2026-09-28  10

    leetcode 141. 环形链表

    字典/哈希

    class Solution: def hasCycle(self, head: ListNode) -> bool: nodemap = defaultdict(int) p = head while p: nodemap[p]+=1 if nodemap[p]>1: return True p = p.next return False

    它还要O(1)内存。能想到的就是依次保存某一个节点,然后判断是否再次访问,但是这样时间不优。

    快慢指针

    快慢指针判断环,这个的确不知道。

    # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: if not head or not head.next: return False turtle = head rabbit = head.next while True: if turtle==rabbit: return True turtle = turtle.next if not rabbit or not rabbit.next: break rabbit = rabbit.next.next return False

    67. 二进制求和

    class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a,2)+int(b,2)).replace('0b','')

    299. 猜数字游戏

    class Solution: def getHint(self, secret: str, guess: str) -> str: count_secret = [0]*10 count_guess = [0]*10 bulls = 0 for i in range(len(secret)): if secret[i]==guess[i]: bulls+=1 else: count_guess[ord(guess[i])-48]+=1 count_secret[ord(secret[i])-48]+=1 return str(bulls)+"A"+str(sum(map(lambda x,y:min(x,y),count_guess,count_secret)))+"B"
    Processed: 0.009, SQL: 9