1683. 无效的推文
1683. 无效的推文
题目
Table: Tweets
+----------------+---------+ | Column Name | Type | +----------------+---------+ | tweet_id | int | | content | varchar | +----------------+---------+tweet_id is the primary key (column with unique values) for this table.
This table contains all the tweets in a social media app.
Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Tweets table:
+----------+-----------------------------------+ | tweet_id | content | +----------+-----------------------------------+ | 1 | Let us Code | | 2 | More than fifteen chars are here! | +----------+-----------------------------------+Output:
+----------+ | tweet_id | +----------+ | 2 | +----------+Explanation:
Tweet 1 has length = 11. It is a valid tweet.
Tweet 2 has length = 33. It is an invalid tweet.
题目大意
表:Tweets
+----------------+---------+ | Column Name | Type | +----------------+---------+ | tweet_id | int | | content | varchar | +----------------+---------+在 SQL 中,tweet_id 是这个表的主键。
这个表包含某社交媒体 App 中所有的推文。
查询所有无效推文的编号(ID)。当推文内容中的字符数严格大于 15 时,该推文是无效的。
以任意顺序 返回结果表。
查询结果格式如下所示:
示例 1:
输入:
Tweets 表:
+----------+-----------------------------------+ | tweet_id | content | +----------+-----------------------------------+ | 1 | Let us Code | | 2 | More than fifteen chars are here! | +----------+-----------------------------------+输出:
+----------+ | tweet_id | +----------+ | 2 | +----------+解释:
推文 1 的长度 length = 14。该推文是有效的。
推文 2 的长度 length = 32。该推文是无效的。
解题思路
解题思路
MySQL
返回字段:
SELECT指定返回字段:tweet_id表示需要返回无效推文的编号。筛选条件:
- 使用
LENGTH(content)函数获取推文内容的字符长度。 - 筛选条件为
LENGTH(content) > 15,即字符数严格大于 15。
- 使用
复杂度分析
- 时间复杂度:
O(n),假设表中有n条记录,需要遍历所有记录来评估字符长度。 - 空间复杂度:SQL 查询本身不占用额外空间,返回的结果占用的空间与满足条件的记录数成正比。
Pandas
加载数据:
将Tweets表加载到 Pandas 的DataFrame中。筛选条件:
使用 Pandas 的布尔索引筛选出content列字符长度严格大于 15 的记录。结果选择:
仅保留无效推文的编号(tweet_id)。
代码
SELECT tweet_id
FROM Tweets
WHERE LENGTH(content) > 15;
import pandas as pd
def find_invalid_tweets(tweets: pd.DataFrame) -> pd.DataFrame:
# 筛选字符长度大于 15 的记录,返回 tweet_id
return tweets[tweets['content'].str.len() > 15][['tweet_id']]
