Leetcode Blind 75 C++: Longest Consecutive Sequence

preview_player
Показать описание
Hey Everyone, Im going over the Blind 75, so decided to make a series on them to help solidify concepts prior to interviews. Below I have attached my notes from doing questions and if have any other questions feel free to let me know!

Thank you
Рекомендации по теме
Комментарии
Автор

//Input
/*
We are given a list of nums
*/

//What DS/Algo/Technique
/*
Hashing-We are able to break u our given data and keep track of each part accordinly
*/

//What to do with the data
/*
We will insert all numbers into a HashSet for fast lookup, then iterate through each number, and check
if it is the first number of a sequence, then count the longest sequence it can form.

Steps:
1. Create a HashSet and add all numbers to it
2. Initialize a variable to track the max length of a sequence
3. Loop through each number in the array
a. Check if it is the first number of a sequence (num-1) doesnt exist in the HashShet
If it is, then count the length of the sequence it can form and update the max length if necessary
4. Return the max length
*/

//Output
/*
Return the length of the longest consecutive elements sequence
*/
class Solution {
public:
int nums) {
//Step 1
unordered_set<int>set(nums.begin(), nums.end());
//step 2
int max_length = 0;
//step 3
for(int num : nums){
//a
if(!set.count(num-1)){
int current_length = 1;

//While (num + 1) exists in the Hashset
while(set.count(num+1)){
num++;
current_length++;
}
max_length = max(max_length, current_length);
}
}
//Step 4
return max_length;
}
};

GChief
Автор

Underrated channel, thx for your efforts 👍

SOME_BORED_GUY
join shbcf.ru