SoFunction
Updated on 2025-03-02

C++ implements LeetCode (128. Find the longest continuous sequence)

[LeetCode] Consecutive Sequence Find the longest continuous sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is

[1, 2, 3, 4]

. Therefore its length is 4.

This question requires the longest continuous sequence and gives the O(n) complexity limitation. Our idea is to use a set HashSet to store all numbers, then iterate through each number in the array. If it exists in the set, then remove it, and then use two variables pre and next to calculate its previous number and the next number, and then loop through the set. If pre is in the set, then remove the set, and then pre is reduced by 1 again until pre is not in the set. The same method is used for next, then next-pre-1 is the longest continuous sequence of the current number, and just update res. Let’s talk about why when detecting that a certain number exists in the set, the number must be removed. This is to avoid a lot of repeated calculations. Take the example in the question as an example. When we traverse to 4, we will traverse downwards 3, 2, and 1. If we do not remove the numbers, when we traverse to 1, we will traverse 2, 3, and 4. Similarly, when traversing to 3, traversing upwards 4, traversing downwards 2, 1, etc. If there are a large number of consecutive numbers in the array, then there will be a large number of repeated calculations, which is very inefficient. Therefore, we need to remove the numbers from the HashSet, and the code is as follows:

C++ Solution 1:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int res = 0;
        unordered_set<int> s((), ());
        for (int val : nums) {
            if (!(val)) continue;
            (val);
            int pre = val - 1, next = val + 1;
            while ((pre)) (pre--);
            while ((next)) (next++);
            res = max(res, next - pre - 1);
        }
        return res;
    }
};

Java Solution 1:

public class Solution {
    public int longestConsecutive(int[] nums) {
        int res = 0;
        Set<Integer> s = new HashSet<Integer>();
        for (int num : nums) (num);
        for (int num : nums) {
            if ((num)) {
                int pre = num - 1, next = num + 1;
                while ((pre)) --pre;
                while ((next)) ++next;
                res = (res, next - pre - 1);
            }
        }
        return res;
    }
}

We can also use a hash table to do it. At the beginning, the HashMap is empty, and then iterate through all numbers. If the number is not in the HashMap, then we will see whether the left and right numbers are in the HashMap respectively. If it is, it will return the mapping value in the hash table. If it is not, it will return 0. Although we can directly take the non-existent mapping value from the HashMap and can also get 0, once we take it, a mapping of 0 will be automatically generated. Then, we will judge that if there is a mapping, it will skip it, and an error will occur. Then we use left+right+1 as the mapping of the current number and update the res result, and update the mapping values ​​of num-left and num-right at the same time.

Let’s explain why you need to skip when judging how the mapping exists. This is because once a certain number creates a mapping, it means that the number has been processed, and the surrounding numbers are likely to have already established a mapping. If you encounter a previously processed number and then take the mapping value of the adjacent number to accumulate, an error will occur. For example, for example, array [1, 2, 0, 1], after 0 is executed, the mapping in HashMap is {1->2, 2->3, 0->3}, it can be seen that the mapping values ​​of 0 and 2 are already 3 at this time. Then if the last 1 is still processed according to the original method, the result will be 7, which is obviously not in line with the question. Also, as mentioned earlier, in order to avoid automatically creating a mapping when accessing non-existent mapping values, we use () to detect it first. Only when there is a mapping, we will get the value from it, otherwise we will directly assign the value to 0. See the code as follows:

C++ Solution 2:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int res = 0;
        unordered_map<int, int> m;
        for (int num : nums) {
            if ((num)) continue;
            int left = (num - 1) ? m[num - 1] : 0;
            int right = (num + 1) ? m[num + 1] : 0;
            int sum = left + right + 1;
            m[num] = sum;
            res = max(res, sum);
            m[num - left] = sum;
            m[num + right] = sum;
        }
        return res;
    }
};

Java Solution 2:

public class Solution {
    public int longestConsecutive(int[] nums) {
        int res = 0;
        Map<Integer, Integer> m = new HashMap<Integer, Integer>();
        for (int num : nums) {
            if ((num)) continue;
            int left = (num - 1) ? (num - 1) : 0;
            int right = (num + 1) ? (num + 1) : 0;
            int sum = left + right + 1;
            (num, sum);
            res = (res, sum);
            (num - left, sum);
            (num + right, sum);
        }
        return res;
    }
}

Similar topics:

Binary Tree Longest Consecutive Sequence

References:

/problems/longest-consecutive-sequence/

/problems/longest-consecutive-sequence/discuss/41055/my-really-simple-java-on-solution-accepted

/problems/longest-consecutive-sequence/discuss/41060/a-simple-csolution-using-unordered_setand-simple-consideration-about-this-problem

This is the article about C++ implementation of LeetCode (128. Find the longest continuous sequence) in this article. For more related C++ implementation, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!