본문 바로가기

Algorithm/MySQL

[LeetCode] 180. Consecutive Numbers (MySQL)

문제

  • 연속해서 세 번 이상 나타나는 모든 숫자를 찾아라
  • 순서 상관없음

코드

  • Join
select distinct a.num as ConsecutiveNums
from logs a
     inner join logs b on a.id = b.id+1
     inner join logs c on a.id = c.id+2
where a.num = b.num
  and a.num = c.num

너무 하드 코딩인 것 같다..
처음에 join 조건을 between 으로 주려다가 num만 값을 빼오는 방법을 모르겠어서 에라 모르겠다 하고 했는데 통과해서 어안이 벙벙함

  • Lead
select distinct sub.num as ConsecutiveNums
from (
    select id   
         , num 
         , lead(num, 1) over (order by Id) as 'lead'
         , lead(num, 2) over (order by Id) as 'lead2'
    from logs
) sub
where sub.num = sub.lead and sub.num = sub.lead2

# [1, 1, 1, 1], 
# [2, 1, 1, 2],
# [3, 1, 2, 1],
# [4, 2, 1, 2], 
# [5, 1, 2, 2],
# [6, 2, 2, null],
# [7, 2, null, null]

한 칸씩 당기는 컬럼과 두 칸씩 당기는 컬럼 열로 두면 첫 번째 행에 id, 첫번째 num, 두번째 num, 세번째 num을 확인할 수 있다.
즉, 연속 세번나오는 num이 1이라는 것을 확인할 수 있다.
이를 from절에 서브쿼리로 두고 첫번째 컬럼과 두번째 컬럼이 같고 첫번째 컬럼과 세번째 컬럼이 같은 조건식을 걸어준다.

  • Lag
select id   
         , num 
         , lag(num, 1) over (order by Id) as 'lag'
         , lag(num, 2) over (order by Id) as 'lag2'
from logs

# [[1, 1, null, null], 
#  [2, 1, 1, null], 
#  [3, 1, 1, 1], 
#  [4, 2, 1, 1], 
#  [5, 1, 2, 1], 
#  [6, 2, 1, 2], 
#  [7, 2, 2, 1]]}

Lag함수도 마찬가지로 한 칸씩 미는 컬럼과 두 칸씩 미는 컬럼을 열로 두면 세번째 행에 id, 첫번째 num, 두번째 num, 세번째 num을 확인할 수 있다.

select distinct sub.num as ConsecutiveNums
from (
    select id   
         , num 
         , lag(num, 1) over (order by Id) as 'lag'
         , lag(num, 2) over (order by Id) as 'lag2'
    from logs
) sub
where sub.num = sub.lag and sub.num = sub.lag2

출처

반응형