'leetcode: longest consecutive sequence'
It blocke me at first for a while, then suddenly I came up with an idea:
first build a map, whose key is the beginning of consective seq and value is end of seq, which is initially equals to the beginning (length of seq is 1).
then we walk through the map, during the walking, join the neighbour seqs and erase from map so we won’t visit twice.
1 | class Solution { |
The same idea can be described in a more concise way in one pass:
This time we build the map on the way. The key is the num, but the value means the length of the sequence which has the key as one of its borders.
we iterate each value in the num array, if it resides in the map, just ignore. Else, we find the two adjcent sequences from left and right, and combine them into one seq. after that, we update the value of the borders of the new seq to the length of the seq.
1 | class Solution2 { |