LeetCode happy brush title fifty-six days --128. Longest Consecutive Sequence

Recent progress can still brush the question, but the form has changed, the feeling because the blind eyes will look so much better on paper. Originally intended to be stored into the folder, but too easily lost, finishing down tomorrow, and quickly took up the

Tonight is the weekend, this week are constantly learning to learn, I think next week is not afraid to take a nap, go back to bed at noon too much temptation for me, I have to think of ways to put a futon door close up , add a cheerful song, noon eat less, refueling small cute

Before owed bad debts, the question too simple finish, resulting in the rest of the problems are, so keep in mind that absolutely no shortcut to go
128 To see the new large flower sauce God, and found very inadequate understanding of the hashtable, and even some common functions do not know is doing
This question is related to knowledge but there are still disjoint-set, fled to escape did not escape.
 
128. Longest Consecutive Sequence
Hard

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

INPUT: [100,. 4, 200 is,. 1,. 3, 2] 
the Output:. 4 
Explanation: Sequence of The Elements longest consecutive IS [1, 2, 3, 4]THEREFORE 4. IS ITS length. 

BONUS:
Auto automatic type inference, the variables for initialization inferred from the expression data types. By auto automatic type inference, we can greatly simplify the programming work. Here are some examples of the use of auto.
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int,int> h;
        int ans=0;
        
        for(int num:nums){
            if(h.count(num)) continue;
            //check whether can find iterator
            auto it_l=h.find(num-1);
            auto it_r=h.find(num+1);
                
            int l=it_l!=h.end()?it_l->second:0;
            int r=it_r!=h.end()?it_r->second:0;
            int t=l+r+1;
            
            h[num]=h[num-l]=h[num+r]=t;
            
            ans=max(ans,t);
        }
        return ans;
    }
};

 

Guess you like

Origin www.cnblogs.com/Marigolci/p/12046855.html