leetcode 刷题128 129
【摘要】
class Solution: def longestConsecutive(self, nums: List[int]) -> int: """ :type nums: List[int] :rtype: int """ nums_hash = set(nums) ans = 0 for num in nums: if num+1 in nums_hash...
class Solution: def longestConsecutive(self, nums: List[int]) -> int: """ :type nums: List[int] :rtype: int """ nums_hash = set(nums) ans = 0 for num in nums: if num+1 in nums_hash: continue count = 0 while num in nums_hash: count += 1 num = num - 1 ans = max(ans,count) return ans
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
class Solution: def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ nums=list(sorted(set(nums))) if not nums: return 0 if len(nums)==1: return 1 first,length=0,1 for last in range(1,len(nums)): if nums[last]!=nums[last-1]+1: first=last else: length=max(length,last-first+1) return length
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object): def sumNumbers(self, root): if root is None: return 0 self.paths = [] self.get_path(root, '') sum = 0 for path in self.paths: sum += int(path) return sum def get_path(self, root, path): if root is None: return if root.left is None and root.right is None: self.paths.append(path + str(root.val)) self.get_path(root.left, path + str(root.val)) self.get_path(root.right, path + str(root.val))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution: def sumNumbers(self, root: TreeNode) -> int: def helper(node, pre): if not node: return 0 if not node.left and not node.right: return node.val + pre * 10 return helper(node.right, pre * 10 + node.val) + helper(node.left, pre * 10 + node.val) return helper(root, 0)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
class Solution: def sumNumbers(self, root, path = 0): if not root: return path path = path * 10 + root.val left = self.sumNumbers(root.left, path) right = self.sumNumbers(root.right, path) if left == path: return right elif right == path: return left else: return left + right
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
文章来源: maoli.blog.csdn.net,作者:刘润森!,版权归原作者所有,如需转载,请联系作者。
原文链接:maoli.blog.csdn.net/article/details/90738704
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)