s-2-3

本文探讨了多种算法的实现,包括判断数字是否为2的幂、寻找数组中缺失的数字、反转链表、检查字符串是否为回文等。同时,介绍了二叉树的翻转、寻找二叉树中两个节点的最近公共祖先、解决 Nim 游戏问题等。此外,还涉及了字符串的异构性检测、数组元素去重以及寻找数组中重复出现的元素。
摘要由CSDN通过智能技术生成

 202 

class Solution:
    def isHappy(self, n: int) -> bool:
        numSet = set()
        while n not in numSet:
            numSet.add(n)
            new = 0
            for i in str(n):
                new += int(i) ** 2
            if new == 1:
                return True
            else:
                n = new
        return False

203

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        dummy = ListNode(0,head)
        node, last = head, dummy

        while node:
            if node.val == val:
                last.next = node.next
            else:
                last = last.next
            node = node.next

        return dummy.next

205

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        dic={}
        for i in range(len(s)):
            if s[i] in dic:
                if dic[s[i]]!=t[i]:
                    return False
            else:
                dic[s[i]]=t[i]
        dic={}
        for i in range(len(t)):
            if t[i] in dic:
                if dic[t[i]]!=s[i]:
                    return False
            else:
                dic[t[i]]=s[i]
        return True

206

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None: return None
        p = head
        cur = None
        pre = None
        while p is not None:
            cur = p.next
            p.next = pre
            pre = p
            p = cur
        return pre   

217

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums) != len(set(nums))

219

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        pos = {}
        for i, num in enumerate(nums):
            if num in pos and i - pos[num] <= k:
                return True
            pos[num] = i
        return False

226

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:return 
        root.left, root.right = self.invertTree(root.right),self.invertTree(root.left)
        return root

228

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        nums.append(2 ** 32)
        ret, start = [], 0
        for i in range(1,len(nums)):
            if nums[i] - nums[i - 1] > 1:
                if i - 1 == start:
                    ret.append(str(nums[start]))
                else:
                    ret.append(f"{nums[start]}->{nums[i - 1]}")
                start = i
        return ret

231

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        # 2 的幂二进制表示只含有一个 1。
        # x & (x - 1) 操作会将 2 的幂设置为 0,因此判断是否为 2 的幂是:判断 x & (x - 1) == 0。
        if n <= 0 :
            return False
        return n & (n-1) == 0

234

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        h = ListNode(0)
        h = head
        l = []
        while h:
            l.append(h.val)
            h = h.next
        return True if l == l[::-1] else False

235

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root.val > max(p.val, q.val):
            return self.lowestCommonAncestor(root.left, p, q)
        elif root.val < min(p.val, q.val):
            return self.lowestCommonAncestor(root.right, p, q)
        else:
            return root

237

        node.val=node.next.val#当前值被后一个值覆盖
        node.next=node.next.next
        

242

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        dic_s = {}
        dic_t = {}
        for i in s:
            if i not in dic_s:
                dic_s[i] = 1
            else:
                dic_s[i] += 1
        for i in t:
            if i not in dic_t:
                dic_t[i] = 1
            else:
                dic_t[i] += 1
        return dic_s == dic_t
        

257

        ans = []
        def helper(root,l=[]):
            if root:
                if root.left == None and root.right == None:
                    l.append(str(root.val))
                    ans.append("->".join(l))
                helper(root.left,l+[str(root.val)])
                helper(root.right,l+[str(root.val)])
        helper(root,[])
        return ans

258

class Solution:
    def addDigits(self, num: int) -> int:
        if num > 9:
            num = num % 9
            if num == 0:
                return 9
        return num

263 choushu

class Solution:
    def isUgly(self, n: int) -> bool:
        if n <= 0:
            return False

        factors = [2, 3, 5]
        for factor in factors:
            while n % factor == 0:
                n //= factor
        
        return n == 1

268

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        num_set = set(nums)
        n = len(nums) + 1
        for number in range(n):
            if number not in num_set:
                return number

278

class Solution:
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        start = 0 
        end = n
        while start < end:
            if end - start ==1:
                return end
            mid = (start+end)//2
            if isBadVersion(mid):
                end = mid
            else:
                start = mid

283

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        zero = 0  # records the position of "0"
        for i in range(len(nums)):
            if nums[i] != 0: #如果该位置不是0
                nums[i], nums[zero] = nums[zero], nums[i]
                zero += 1

290

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        word2ch = dict()
        ch2word = dict()
        words = s.split()
        if len(pattern) != len(words):
            return False
        
        for ch, word in zip(pattern, words):
            if (word in word2ch and word2ch[word] != ch) or (ch in ch2word and ch2word[ch] != word):
                return False
            word2ch[word] = ch
            ch2word[ch] = word
    
        return True

292

class Solution:
    def canWinNim(self, n: int) -> bool:
        return n % 4 != 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值