SQL

[Leetcode/SQL] 180. Consecutive Numbers

지구인 ㅣ 2022. 8. 15. 10:46

728x90

SQL Schema:

Create table If Not Exists Logs (id int, num int)
Truncate table Logs
insert into Logs (id, num) values ('1', '1')
insert into Logs (id, num) values ('2', '1')
insert into Logs (id, num) values ('3', '1')
insert into Logs (id, num) values ('4', '2')
insert into Logs (id, num) values ('5', '1')
insert into Logs (id, num) values ('6', '2')
insert into Logs (id, num) values ('7', '2')

 

Table: Logs

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+
id is the primary key for this table.
id is an autoincrement column.

 

연속적으로 3번 이상 같은 num일 경우의 num을 반환하라. 단 순서는 무관하다.

 

Example 1:

Input: 
Logs table:
+----+-----+
| id | num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+
Output: 
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+
Explanation: 1 is the only number that appears consecutively for at least three times.

 

 

Code:

# case 1
SELECT DISTINCT l1.Num AS ConsecutiveNums
FROM Logs l1, Logs l2, Logs l3
WHERE
    l1.Id = l2.Id - 1
    AND l2.Id = l3.Id - 1
    AND l1.Num = l2.Num
    AND l2.Num = l3.Num;

# case 2
# 3짜리 window의 num이 모두 같은지 검토
# 매우 빠름
select distinct Num as ConsecutiveNums
from Logs
where (Id + 1, Num) in (select * from Logs) and (Id + 2, Num) in (select * from Logs)

- case 1은 가장 단순한 방법으로, 예시코드와 같다. 로그 객체 3개를 만들어서, 연속된 3개의 id로 설정 후 num값이 같은지 비교한다.

 

- case 2는  where ~ in ~  과 같은 형식을 취해 문제를 푼다. where 절에 많은 select-from문이 들어가 시간이 오래 걸릴 줄 알았는데 런타임 약 390ms로 매우 빨랐다. 단순한 select문일 경우 별다른 계산과정이 없으므로, and 연산보다 빠른 것이 아닐까 싶다..

 

그리고  where "element" in select * from 의 구조에서 where 다음의 "element" 부분에 ()와 같은 형식을 쓸 수 있다는 생각을 못했는데 처음 알았다.

 

 

728x90