美文网首页
128.Longest Consecutive Sequence

128.Longest Consecutive Sequence

作者: gpfworld | 来源:发表于2019-05-05 16:20 被阅读0次

    题目描述:

    https://leetcode.com/problems/longest-consecutive-sequence/

    Code:

    //mycode
    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            set<int> tp_st( nums.begin() , nums.end() );
            vector<int> tp_nums( tp_st.begin(), tp_st.end() );
            if( tp_nums.size() != 0){
                int maxlength = 1;
                int begin = 0 ;
                sort(tp_nums.begin(), tp_nums.end());
                for (int i = 0; i < tp_nums.size() -1 ; i++) {
                    if (tp_nums.at(i+1) != tp_nums.at(i) + 1) {
                        int tp_len = i - begin + 1;
                        if (tp_len > maxlength) {
                            maxlength = tp_len;
                        }
                        begin = i + 1;
                    }
                }
                int tp_len = tp_nums.size() - begin ;
                if (tp_len > maxlength) {
                    maxlength = tp_len;
                }
                return maxlength;
            }else{
                return 0;
            }
        }
    };
    //other people's good solution
    
    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            int res = 0;
            unordered_map<int, int> m;
            for (int d : nums) {
                if (!m.count(d)) {
                    int left = m.count(d - 1) ? m[d - 1] : 0;
                    int right = m.count(d + 1) ? m[d + 1] : 0;
                    int sum = left + right + 1;
                    m[d] = sum;
                    res = max(res, sum);
                    m[d - left] = sum;
                    m[d + right] = sum;
                }
            }
            return res;
        }
    };
    

    相关文章

      网友评论

          本文标题:128.Longest Consecutive Sequence

          本文链接:https://www.haomeiwen.com/subject/hxfswqtx.html