17ms Pass C++ Solution

  • -37

    I don't understand why this question is hard.
    Anyways, the basic idea is if num[i] == num[i-1], skip it; if num[i] != num[i-1]+1, stop counting the length and store the longer one. I comment inline as well.

    int longestConsecutive(vector<int> &num) {
        int n = (int)num.size();
        if (n < 2) {
            return n;
        int maxlen = -1;
        int len = 0;
        sort(num.begin(), num.end()); //nlogn
        for (int i=1; i<n; i++) {
            if (num[i] == num[i-1]) { // Same number, skip it
            if (num[i] != num[i-1]+1) { // Not consecutive, store the longer one. 
                if (maxlen < len) 
                    maxlen = len;
                len=0; // Restart length counting
        return max(maxlen, len+1);

  • 9

    time complexity for sorting is NlogN, not logN

  • 0

    Thank you for pointing out. Fixed.

Log in to reply

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