Skip to content

Commit 792f1cd

Browse files
committed
#240 longest-consecutive-sequence solution
1 parent 969f0a8 commit 792f1cd

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
ํ’€์ด :
3+
ํ•ด์‹œํ…Œ์ด๋ธ”์— nums๋ฅผ ๋‹ด์€ ๋’ค num - 1์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š” num์— ๋Œ€ํ•ด์„œ๋งŒ (์ค‘๊ฐ„์ ์—์„œ๋Š” ๊ณ„์‚ฐํ•˜์ง€ ์•Š๊ธฐ ์œ„ํ•ด)
4+
๊ธธ์ด๋ฅผ ์ฆ๊ฐ€์‹œ์ผœ ๋‚˜๊ฐ€๋ฉฐ ์—ฐ์†๋œ ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๊ณ  cur์˜ max๊ฐ’ ans๋ฅผ ๊ตฌํ•œ๋‹ค
5+
6+
nums์˜ ๊ฐฏ์ˆ˜ N
7+
TC : O(N)
8+
์ด์ค‘ for๋ฌธ์ด์ง€๋งŒ ๋‚ด๋ถ€ for๋ฌธ์€ num - 1์ด ์—†์„๋•Œ๋งŒ ์—ฐ์†๋œ ํ•ด์‹œํ…Œ์ด๋ธ” ๋‚ด๋ถ€ ๊ฐ’์— ๋Œ€ํ•ด์„œ ์ˆ˜ํ–‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์— O(N)
9+
10+
SC : O(N)
11+
ํ•ด์‹œํ…Œ์ด๋ธ”์˜ ํฌ๊ธฐ๋Š” N์— ๋น„๋ก€
12+
*/
13+
14+
#include <vector>
15+
#include <unordered_set>
16+
using namespace std;
17+
18+
class Solution {
19+
public:
20+
int longestConsecutive(vector<int>& nums) {
21+
int cur;
22+
int ans = 0;
23+
unordered_set<int> us(nums.begin(), nums.end());
24+
25+
for (auto& num : us)
26+
{
27+
if (us.find(num - 1) == us.end())
28+
{
29+
cur = 1;
30+
for(int i = 1; us.find(num + i) != us.end(); i++)
31+
cur++;
32+
ans = max(ans, cur);
33+
}
34+
}
35+
return ans;
36+
}
37+
};

0 commit comments

Comments
ย (0)