128. Longest Consecutive Sequence Whenever a new element n is inserted into the map, do two things:

  • See if n - 1 and n + 1 exist in the map, and if so, it means there is an existing sequence next to n. Variables left and right will be the length of those two sequences, while 0 means there is no sequence and n will be the boundary point later. Store (left + right + 1) as the associated value to key n into the map.
  • Use left and right to locate the other end of the sequences to the left and right of n respectively, and replace the value with the new length.
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int,int> seqMap;
        int ret=0;
        for(int n : nums){
            if(!seqMap.count(n)){
                int l = seqMap.count(n-1)?seqMap[n-1]:0 ;//此处查找必须用count 直接用[]的话没有会创造个val为0的entry然后下次if(!seqMap.count(n)) return false
                int r = seqMap.count(n+1)?seqMap[n+1]:0;
                int sum = l+r+1;
                seqMap[n] = sum;
                ret = max(ret,sum);
                seqMap[n-l] = sum;//extend till l
                seqMap[n+r] = sum;//extend till r

            }
        }
        return ret;
    }
};

results matching ""

    No results matching ""