↓快轉到主要內容
  1. LeetCode/

LeetCode 197: Rising Temperature

·1 分鐘· ·
LeetCode Easy Database
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2021-10-10

  • 提交紀錄:Runtime Error → Accepted

解題思路
#

把每一天接到「前一天」(SQL 模板三):DATEDIFF(w.recordDate, y.recordDate) = 1,再過濾 w.temperature > y.temperature。不能用 id 相鄰代表日期相鄰,id 的順序不一定跟日期一樣,日期也可能有缺。

我的嘗試
#

第一版 join 的寫法打錯,JOIN weather,w 多了一個逗號(RE);拿掉就 AC 了。

正確解法
#

SELECT w.id
FROM Weather w
JOIN Weather y ON DATEDIFF(w.recordDate, y.recordDate) = 1
WHERE w.temperature > y.temperature;

複雜度
#

self join,有日期索引時接近 O(n)。

要特別避免的錯誤
#

  • 用日期判斷前一天,不要用 id。
  • DATEDIFF 是 MySQL 的函數,其他資料庫的寫法不同(例如 date - interval)。

面試口說整理
#

我把 Weather 跟自己 join,條件是兩筆的日期差剛好一天,再留下今天比前一天熱的 id。前一天要用日期判斷,id 的順序不一定跟日期一樣。

相關文章

LeetCode 595: Big Countries
·1 分鐘
LeetCode Easy Database
LeetCode 595 解題筆記:面積至少 300 萬或人口至少 2500 萬,用 WHERE 加 OR 過濾
LeetCode 596: Classes With at Least 5 Students
·1 分鐘
LeetCode Easy Database
LeetCode 596 解題筆記:按 class 分組,HAVING COUNT(DISTINCT student) >= 5;舊版測資有重複的列,要數不同的學生
LeetCode 620: Not Boring Movies
·1 分鐘
LeetCode Easy Database
LeetCode 620 解題筆記:id 是奇數而且 description 不是 boring,按 rating 由高到低排序
LeetCode 175: Combine Two Tables
·1 分鐘
LeetCode Easy Database
LeetCode 175 解題筆記:沒有地址的人也要出現,所以用 LEFT JOIN,對不到的 city、state 會是 NULL
LeetCode 181: Employees Earning More Than Their Managers
·1 分鐘
LeetCode Easy Database
LeetCode 181 解題筆記:Employee 跟自己 self join,用 managerId = id 把員工和主管接起來,再比較薪水
LeetCode 182: Duplicate Emails
·1 分鐘
LeetCode Easy Database
LeetCode 182 解題筆記:按 email 分組,HAVING COUNT(*) > 1 留下出現超過一次的