Simple and straightforward c++ solution


  • 0
    S

    The idea is simple: sort the array and remove the duplicates and scan the array for the sequence

    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            if(!nums.size()) return 0;
            sort(nums.begin(),nums.end());//if it has duplicates this would be messed up!
            nums.erase(unique(nums.begin(),nums.end()),nums.end());
            int maxlen=1;
            //check the jump non-1 to 1 start, from 1 to non-1 is end
            //scan the whole sequence
            int ind0=0,ind1=0;
            
            for(int i=1;i<nums.size();i++)
            {
                if(nums[i]==nums[i-1]+1)
                    ind1=i;
                else
                {
                    if(ind1) maxlen=max(maxlen,ind1-ind0+1);
                    ind0=i;
                }
            }
            if(ind1) maxlen=max(maxlen,ind1-ind0+1);
            return maxlen;
        }
    };
    

Log in to reply
 

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