File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You canโt perform that action at this time.
0 commit comments