Does hashmap works for this question?


  • 0
    X
    //longest consectutive sequence
    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            if (nums.size() == 0) return 0;
            map<int, int> freq;
            for (auto num : nums) freq[num]++;
            
            auto start = freq.begin();
            auto it = freq.begin();
            int longestLen = -1;
            
            while (it != freq.end()) {
                auto nextIt = it; nextIt++;
                if (nextIt != freq.end()) {
                    if (nextIt->first == it->first + 1) {
                        it = nextIt;
                    } else {
                        longestLen = max(longestLen, distance(start, it) + 1 );
                        it = nextIt;
                        start = nextIt;
                    }
                } else {
                    longestLen = max(longestLen, distance(start, it) + 1); break;
                }
            }
            
            return longestLen;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.