Beats 97% simple C++ solution, 13ms


  • 0
    W
    int longestConsecutive(vector<int>& nums) {
            if (nums.empty()) return 0;
            sort(nums.begin(), nums.end());
            stack<pair<int, int>> stk;
            stk.emplace(nums[0], 1);
            for (int i=1; i<nums.size(); i++) {
                if (nums[i] == stk.top().first) {
                    continue;
                } else if (nums[i] == stk.top().first + 1) {
                    stk.top().first = nums[i];
                    stk.top().second++;
                } else {
                    stk.emplace(nums[i], 1);
                }
            }
            
            int result = 0;
            while (!stk.empty()) {
                result = max(result, stk.top().second);
                stk.pop();
            }
            
            return result;
        }
    
    

Log in to reply
 

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