C++ simple & short solution

google
Tags: #<Tag:0x00007f1828e1e5a0>

#1

Comment body goeint Solution::longestConsecutive(const vector &A) {
priority_queue q;
set s;
for(int i : A)s.insert(i);

for(int i: s){
    q.push(i);
}

int prev, current;
prev = q.top();
q.pop();
int ans = 1;
int mx = INT_MIN;
while(!q.empty()){
    current = q.top();
    q.pop();
    if(abs(prev - current) == 1){
        ans++;
        mx = max(mx, ans);
    }
    else{
        mx = max(mx, ans);
        ans = 1;
    }
    prev = current;
}
return max(mx, ans);

}
s here.


#2

Your solution’s time complexity is O(nlogn) while the expected is O(n). Insertion and deletion in priority queue 1 element at a time will take O(nlogn).