Notice
Recent Posts
Recent Comments
Link
복's
[ LeetCode - 180 ] Consecutive Numbers 본문
728x90
https://leetcode.com/problems/consecutive-numbers/
Consecutive Numbers - LeetCode
Can you solve this real interview question? Consecutive Numbers - Table: Logs +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ In SQL, id is the primary key for this table.
leetcode.com
LAG, LEAD 함수를 통해서 이전 row의 값과 다음 row의 값을 가져와서 문제를 풀었다.
사실 두 함수를 알고 있지는 않았고, 서칭을 통해서 알게 되었다.
sql을 책이나 자료를 통해서 처음부터 공부한게 아니라는게 티가 나는 문제였다....sw정글 끝나면 반드시 공부 하도록...
[ 📌 풀이 ]
내가 푼 방법은 비교적으로 간단하고 이해하기 쉬운 형태인거 같다. (다른 고수들의 코드를 보았을 때)
- 현 row의 이전(prev)과 다음(next)와 같다면 출력 하도록 했다.
- 출력시 중복 값이 나올 수 있어서 group by 혹은 distinct를 사용해서 중복을 제거할 수 있다.
distinct가 더 빠른 속도가 나왔는데 그룹핑 하는게 출력할 rows에서 중복 제거하는 것보다 오래 걸리는거 같다.
다른 풀이로는 셀프 조인(self join)을 이용해서 풀거나 dense_rank 풀이법을 봤는데 나는 내 풀이가 가장 직관적인 것 같다.
[ 📌 코드 - Oracle ]
-- Author : Lee In Bok
-- Date : 2023.11.25(Sat)
-- Spend Time: 16m 36s
-- Runtime : 1035 ms (Beats 68.61%)
-- Algoritm : LAG, LEAD
select distinct num as ConsecutiveNums
from(select num
, LAG(num) over(order by id) as prev_num
, LEAD(num) over(order by id) as next_num
from Logs)
where num = prev_num
and num = next_num
;
[ 📌 결과 - Oracle ]
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[ LeetCode - 104 ] Maximum Depth of Binary Tree (1) | 2023.12.01 |
---|---|
[ LeetCode - 1189 ] Maximum Number of Balloons (1) | 2023.11.26 |
[ LeetCode - 178 ] Rank Scores (2) | 2023.11.20 |
[ LeetCode - 176 ] Second Highest Salary (1) | 2023.11.18 |
[ LeetCode - 100 ] Same Tree (1) | 2023.11.14 |