leetcode No128. Longest Consecutive Sequence

Question:

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

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

Algorithm:

建立hash表,unordered_map<int,bool> hash
int存元素,bool用于判断元素是否使用过
从元素往前找,记录大小
从元素往后找,记录大小
如果元素使用过的就不找了

Accepted Code:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if(nums.size()<=1)
            return nums.size();
        unordered_map<int,bool> hash;    //这里应使用无序容器,map是有序,已经是nlogn的复杂度
        for (int i = 0; i < nums.size(); i++){
		    hash[nums[i]] = true;
	    }
        int res=0;
        int count=1;
        for(int i=0;i<nums.size();i++){
            if(hash[nums[i]]==true){
                count=1;
                int left=nums[i]-1;
                int right=nums[i]+1;
                while(hash[left]==true){
                    hash[left]=false;
                    count++;
                    left--;
                }
                while(hash[right]==true){
                    hash[right]=false;
                    count++;
                    right++;
                }
            }
            if(res<count)
                res=count;
        }
        return res;
    }
};


你可能感兴趣的:(LeetCode)