101
题目描述:
给定一个二叉树,检查它是否是镜像对称的。
示例:
解答:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def check(node1, node2):
if not node1 and not node2:
return True
elif not node1 or not node2:
return False
if node1.val != node2.val:
return False
return check(node1.left, node2.right) and check(node1.right, node2.left)
return check(root, root)
121
题目描述:
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例:
解答:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
min_input = prices[0]
max_profit = 0
for p in prices[1:]:
min_input = min(p, min_input)
max_profit = max(max_profit, p - min_input)
return max_profit
706
题目描述:
不使用任何内建的哈希表库设计一个哈希映射(HashMap)。
实现 MyHashMap 类:
MyHashMap() 用空映射初始化对象
void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。如果 key 已经存在于映射中,则更新其对应的值 value 。
int get(int key) 返回特定的 key 所映射的 value ;如果映射中不包含 key 的映射,返回 -1 。
void remove(key) 如果映射中存在 key 的映射,则移除 key 和它所对应的 value 。
示例:
解答:
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.data=[-1]*1000001
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
self.data[key]=value
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped,
or -1 if this map contains no mapping for the key
"""
return self.data[key]
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
self.data[key]=-1
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
面试题16.05
题目描述:
设计一个算法,算出 n 阶乘有多少个尾随零。
示例:
解答:
class Solution:
def trailingZeroes(self, n: int) -> int:
#数5的个数即可。0是由5*2产生的,偶数的数量多于5。
#每五个数中其中一个数有因子5,在这些数中又每五个又有一个因子5(比如25)
cnt=0
while n >= 5:
cnt += n // 5
n=n//5
return cnt
面试题16.17
题目描述:
给定一个整数数组,找出总和最大的连续数列,并返回总和。
示例:
解答:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_value, cur_value = nums[0], 0
for num in nums:
cur_value += num
max_value = max(max_value, cur_value)
cur_value = max(cur_value, 0)
return max_value