My Simple C++ Solution Using unordered_set ,O(n) time.


  • 1
    H
    class Solution {
        public:
            int longestConsecutive(vector<int>& nums) {
                unordered_set<int> st(nums.begin(),nums.end());
                int ret = 0;
                while(st.size())
                {
                    int x = *st.begin();
                    int left = x,right = x+1;
                    while(st.count(left))
                        st.erase(left--);
                    while(st.count(right))
                        st.erase(right++);
                    ret = max(ret,right - left  - 1);
                }
            return ret;
        }
    };

Log in to reply
 

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