Skip to content

Latest commit

 

History

History
179 lines (142 loc) · 4.09 KB

1683.md

File metadata and controls

179 lines (142 loc) · 4.09 KB
title description keywords
1683. 无效的推文
LeetCode 1683. 无效的推文题解,Invalid Tweets,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
1683. 无效的推文
无效的推文
Invalid Tweets
解题思路
数据库

1683. 无效的推文

🟢 Easy  🔖  数据库  🔗 力扣 LeetCode

题目

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

  1. 返回字段
    SELECT 指定返回字段:tweet_id 表示需要返回无效推文的编号。

  2. 筛选条件

    • 使用 LENGTH(content) 函数获取推文内容的字符长度。
    • 筛选条件为 LENGTH(content) > 15,即字符数严格大于 15。

复杂度分析

  • 时间复杂度O(n),假设表中有 n 条记录,需要遍历所有记录来评估字符长度。
  • 空间复杂度:SQL 查询本身不占用额外空间,返回的结果占用的空间与满足条件的记录数成正比。

Pandas

  1. 加载数据
    Tweets 表加载到 Pandas 的 DataFrame 中。

  2. 筛选条件
    使用 Pandas 的布尔索引筛选出 content 列字符长度严格大于 15 的记录。

  3. 结果选择
    仅保留无效推文的编号(tweet_id)。

代码

::: code-tabs @tab MySQL

SELECT tweet_id
FROM Tweets
WHERE LENGTH(content) > 15;

@tab Pandas

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']]

:::