https://leetcode.com/problems/longest-consecutive-sequence/submissions/2166160484/
Longest Consecutive Sequence - LeetCode
Can you solve this real interview question? Longest Consecutive Sequence - Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input:
leetcode.com
연속된 수열을 찾는 문제입니다.
다만 복잡도가 O(n)으로서 동작해야합니다.
만약에 정렬되어있었다면 그대로 훑어가면서 확인하면 되었겠지만 순서자체가 랜덤으로 섞여있어서 불가능합니다.
그리고 sort자체는 보통 O(NlogN)이기 때문에 사용해서 훑는 것도 불가능합니다. 따라서 Hash를 사용해 찾는 unordered_set을 이용했습니다.
연속된 값을 찾기 위해서 만약의 set의 element x를 순회할 때 x-1이 존재하지 않는다면 해당 sequence의 시작점이 될것이고 아니라면 이미 앞에 무엇이 있기 때문에 해당 숫자에 대해 탐색할 필요가 없을 것입니다.
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
int ans = 0;
for (int x : s)
{
if (s.find(x - 1) == s.end())
{
int current = x;
int length = 1;
while (s.find(current + 1) != s.end())
{
++current;
++length;
}
ans = max(ans, length);
}
}
}
};
'Algorithm > PS' 카테고리의 다른 글
| Leetcode[two pointer] 3Sum 풀어보기 (0) | 2026.10.09 |
|---|---|
| [Leetcode][PrefixSum] Merge Intervals 풀어보기 (0) | 2026.10.06 |
| [Leetcode][Greedy] Merge Intervals 풀어보기 (0) | 2026.09.28 |
| [LeetCode][Dijkstra] NetworkDelayTime 풀어보기 (0) | 2026.09.26 |
| [LeetCode][DFS] Find Eventual 어쩌구 풀어보기 (0) | 2026.09.25 |