Skip to content

Commit 475cc7c

Browse files
committed
longest-consecutive-sequence solution
1 parent 37ec25d commit 475cc7c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
int longestConsecutive(vector<int>& nums) {
4+
unordered_map<int, int> count;
5+
// nums์— ํ•ด๋‹นํ•˜๋Š” index๋Š” 1์„ ํ‘œ์‹œ
6+
for (int num: nums) {
7+
count[num] = 1;
8+
}
9+
10+
vector<pair<int, int>> order(count.begin(), count.end());
11+
sort(order.begin(), order.end(), [](auto& a, auto& b) {return a.first < b.first;});
12+
13+
int length = 1;
14+
int currentLength = 1;
15+
if(order.empty()) return 0;
16+
for (int i = 1; i < order.size(); i++) {
17+
// ์—ฐ์†์ ์ธ์ง€ ํ™•์ธ
18+
if (order[i].first == order[i-1].first +1)
19+
currentLength++;
20+
else
21+
currentLength = 1;
22+
length = max(length, currentLength);
23+
}
24+
25+
return length;
26+
}
27+
};
28+

0 commit comments

Comments
ย (0)