31ms C++ solution, any idea to make it faster?


  • 0
    E

    code as following:

    int longestConsecutive(vector<int> &num) {
            unordered_map<int,int> s;
            int longest=1;
            for(int i:num)
            {
                if(s.find(i)==s.end())
                {
                 s[i]=1;
                 int left=s.find(i-1)!=s.end()?(i-s[i-1]):i;
                 int right=s.find(i+1)!=s.end()?(i+s[i+1]):i;
                 s[left]=s[right]=right-left+1;
                 longest=s[right]>longest?s[right]:longest;
                }
            }
            return longest;
        }

  • 0
    W

    The solution should be in logarithmic complexity. The complexity of your solution is O(n).


Log in to reply
 

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