LeetCode--1204. 最后一个能进入巴士的人

150 阅读2分钟

1 题目描述

表: Queue

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| person_id   | int     |
| person_name | varchar |
| weight      | int     |
| turn        | int     |
+-------------+---------+

person_id 是这个表具有唯一值的列。 该表展示了所有候车乘客的信息。 表中 person_id 和 turn 列将包含从 1 到 n 的所有数字,其中 n 是表中的行数。 turn 决定了候车乘客上巴士的顺序,其中 turn=1 表示第一个上巴士,turn=n 表示最后一个上巴士。 weight 表示候车乘客的体重,以千克为单位。

有一队乘客在等着上巴士。然而,巴士有1000  千克 的重量限制,所以其中一部分乘客可能无法上巴士。

编写解决方案找出 最后一个 上巴士且不超过重量限制的乘客,并报告 person_name 。题目测试用例确保顺位第一的人可以上巴士且不会超重。

2 测试用例

输入:

Queue 表

+-----------+-------------+--------+------+
| person_id | person_name | weight | turn |
+-----------+-------------+--------+------+
| 5         | Alice       | 250    | 1    |
| 4         | Bob         | 175    | 5    |
| 3         | Alex        | 350    | 2    |
| 6         | John Cena   | 400    | 3    |
| 1         | Winston     | 500    | 6    |
| 2         | Marie       | 200    | 4    |
+-----------+-------------+--------+------+

输出:

+-------------+
| person_name |
+-------------+
| John Cena   |
+-------------+

解释: 为了简化,Queue 表按 turn 列由小到大排序。

+------+----+-----------+--------+--------------+
| Turn | ID | Name      | Weight | Total Weight |
+------+----+-----------+--------+--------------+
| 1    | 5  | Alice     | 250    | 250          |
| 2    | 3  | Alex      | 350    | 600          |
| 3    | 6  | John Cena | 400    | 1000         | (最后一个上巴士)
| 4    | 2  | Marie     | 200    | 1200         | (无法上巴士)
| 5    | 4  | Bob       | 175    | ___          |
| 6    | 1  | Winston   | 500    | ___          |
+------+----+-----------+--------+--------------+

3 解题思路

  1. turn 升序统计 turn 的范围是 1 ~ turn 的累积重量 total_weight
select person_name,  
	   turn,  
	   sum(weight) over (order by turn) as total_weight  
from Queue

执行结果

+-----------+----+------------+
|person_name|turn|total_weight|
+-----------+----+------------+
|Alice      |1   |250         |
|Alex       |2   |600         |
|John Cena  |3   |1000        |
|Marie      |4   |1200        |
|Bob        |5   |1375        |
|Winston    |6   |1875        |
+-----------+----+------------+
  1. 查询出累积重量 <=1000KG 的数据 total_weight <= 1000
select *  
from (select person_name,  
             turn,  
             sum(weight) over (order by turn) as total_weight  
      from Queue) as q  
where total_weight <= 1000

执行结果

+-----------+----+------------+
|person_name|turn|total_weight|
+-----------+----+------------+
|Alice      |1   |250         |
|Alex       |2   |600         |
|John Cena  |3   |1000        |
+-----------+----+------------+
  1. 获取最后一个满足上车条件的乘客信息,需要对 total_weight 倒序排序,使用分页获取第一条数据
select person_name  
from (select person_name,  
             turn,  
             sum(weight) over (order by turn) as total_weight  
      from Queue) as q  
where total_weight <= 1000  
order by total_weight desc  
limit 1;

执行结果

+-----------+
|person_name|
+-----------+
|John Cena  |
+-----------+