LeetCode 精选 TOP 面试题 - Easy series (4)
本篇要开始坚持刷题了,从Leetcode精选面试section开始,本文是easy series题解的记录,会不断更新维护。
104. 二叉树的最大深度

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if (root==None): # 递归出口
return 0
else:
l=self.maxDepth(root.left)
r=self.maxDepth(root.right)
return max([l,r])+1
234. 回文链表:请判断一个链表是否为回文链表。
时空效率不高的解法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
lst=[]
if head!=None:
while head.next!=None:
lst.append(str(head.val))
head=head.next
lst.append(str(head.val))
flag=True
for i in range(len(lst)//2):
if lst[i]!=lst[len(lst)-1-i]:
flag=False
return flag
else: # [] Null
return True
优化:
237. 删除链表中的节点
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点。传入函数的唯一参数为 要被删除的节点 。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val=node.next.val
node.next=node.next.next
412. Fizz Buzz

class Solution:
def fizzBuzz(self, n: int) -> List[str]:
res=[]
for i in range(1,n+1):
if i%3==0 and i%5!=0:
res.append('Fizz')
elif i%5==0 and i%3!=0:
res.append('Buzz')
elif i%5==0 and i%3==0:
res.append('FizzBuzz')
else:
res.append(str(i))
return res
浙公网安备 33010602011771号