每日一题 day2

51 阅读2分钟

力扣 112 路经总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 

叶子节点 是指没有子节点的节点。

方法一:递归。

# 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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root://跟节点为空 返回错误
            return False
        if not root.left and not root.right://当前节点为叶子结点 且 路径总和刚好为targetSum
            return root.val == targetSum
        return self.hasPathSum(root.left,targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)//递归左子树和右子树 判断是否满足题目条件

方法二:广度优先算法(BFS)
思路:对整个树进行广度优先遍历 维护两个队列 一个用于存储结点 一个用于存储从跟节点到当前节点的值

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        pop_node = deque([root]) //广度优先遍历节点
        pop_val = deque([root.val]) //并存储跟节点到当前节点的值
        while pop_node: //为遍历完所有节点
            now = pop_node.popleft() //当前节点
            temp = pop_val.popleft() //跟节点到当前节点的值
            if not now.left and not now.right: //当前节点为叶子结点
                if temp == targetSum: //跟节点到当前节点的值符合条件
                    return True 
                continue //继续执行循环
            if now.left: //左节点不为空 将其加入队列中
                pop_node.append(now.left) //节点入队列
                pop_val.append(now.left.val + temp) //累加值入队列
            if now.right: //右节点不为空 将其加入队列中
                pop_node.append(now.right) //节点入队列
                pop_val.append(now.right.val + temp) //累价值入队列
        return False

力扣511 游戏玩法分析 I
活动表 Activity

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
+--------------+---------+SQL 中,表的主键是 (player_id, event_date)。
这张表展示了一些游戏玩家在游戏平台上的行为活动。
每行数据记录了一名玩家在退出平台之前,当天使用同一台设备登录平台后打开的游戏的数目(可能是 0 个)。

查询每位玩家 第一次登录平台的日期

查询结果的格式如下所示:

Activity 表:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-05-02 | 6            |
| 2         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-02 | 0            |
| 3         | 4         | 2018-07-03 | 5            |
+-----------+-----------+------------+--------------+

Result 表:
+-----------+-------------+
| player_id | first_login |
+-----------+-------------+
| 1         | 2016-03-01  |
| 2         | 2017-06-25  |
| 3         | 2016-03-02  |
+-----------+-------------+

结果:使用GROUP BY利用player_id将表进行分组,再输出其中event_date最小的组

SELECT A.player_id, Min(event_date) AS first_login 
from Activity AS A 
GROUP BY A.player_id;