Skip to content

Commit 2b1c885

Browse files
Added (LEETCODE) Longest Consecutive Sequence.cpp in Arrays
1 parent 7328537 commit 2b1c885

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
2+
3+
// You must write an algorithm that runs in O(n) time.
4+
5+
6+
7+
// Example 1:
8+
9+
// Input: nums = [100,4,200,1,3,2]
10+
// Output: 4
11+
// Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
12+
// Example 2:
13+
14+
// Input: nums = [0,3,7,2,5,8,4,6,0,1]
15+
// Output: 9
16+
17+
18+
// Constraints:
19+
20+
// 0 <= nums.length <= 105
21+
// -109 <= nums[i] <= 109
22+
23+
// My Solution:
24+
25+
class Solution {
26+
public:
27+
int longestConsecutive(vector<int>& nums) {
28+
if(nums.size() == 0)
29+
return 0;
30+
sort(nums.begin(), nums.end());
31+
32+
int cus = 1;
33+
int maxs = 1;
34+
35+
for(int i=1;i<nums.size();i++){
36+
if(nums[i]!=nums[i-1]){
37+
if(nums[i] == nums[i-1]+1){
38+
cus+=1;
39+
}
40+
else{
41+
maxs = max(maxs,cus);
42+
cus = 1;
43+
}
44+
}
45+
}
46+
return max(maxs,cus);
47+
}
48+
};

0 commit comments

Comments
 (0)