Longest Consecutive Sequence Algorithm
The Longest Consecutive Sequence Algorithm is a technique used to find the length of the longest consecutive sequence of numbers in an unsorted array. This algorithm is designed to efficiently identify the maximum sequence of successive integers present in the given array while minimizing the need for sorting or complex data manipulation. In various applications, such as data analysis and pattern recognition, the ability to identify consecutive sequences can be critical for understanding the underlying structure and relationships within the data.
The algorithm works by iterating through the array and using a hash set to store the unique elements. The hash set allows for efficient lookup and insertion operations, making it ideal for solving this problem. Once the elements are stored in the hash set, the algorithm iterates through the unique elements and checks if the current element is the start of a sequence, i.e., if the element minus one is not present in the hash set. If a sequence is found, the algorithm then iteratively checks for consecutive elements in the hash set, incrementing a counter for each found element. The maximum length of the sequence encountered during this process is considered the longest consecutive sequence in the array. This approach significantly reduces the time complexity as compared to sorting-based methods, resulting in an efficient solution to the problem.
class Solution {
public:
int longestConsecutive(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
priority_queue<int> Q;
for (int i = 0; i < num.size(); i++) {
Q.push(num[i]);
}
int ret = 1;
int maxlen = 1;
int temp = Q.top();
Q.pop();
while (!Q.empty()) {
if (temp - 1 == Q.top()) {
temp -= 1;
maxlen += 1;
} else if (temp != Q.top()) {
temp = Q.top();
maxlen = 1;
}
Q.pop();
ret = max(maxlen, ret);
}
return ret;
}
};
// O(n) solution
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int, int> longest;
int result = 0;
for (int i = 0; i < num.size(); i++) {
if (longest[num[i]] != 0) {
continue;
}
int leftbound = longest[num[i]-1];
int rightbound = longest[num[i]+1];
int bound = leftbound + rightbound + 1;
longest[num[i]] = bound;
longest[num[i]-leftbound] = bound;
longest[num[i]+rightbound] = bound;
if (result < bound) {
result = bound;
}
}
return result;
}
};