[LeetCode]Longest Consecutive Sequence

class Solution {
public:
	int longestConsecutive(vector<int> &num) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		//O(n) to find the longest consecutive sequence so we need to use O(1) hash table
		//unordered_set is an appropriate one
		unordered_set<int> hashTable;
		for(int i = 0; i < num.size(); ++i)
			hashTable.insert(num[i]);
		//enumerate every hash value
		unordered_set<int> visitedTable;//keep the visit status of hash value
		int maxLen = 1;
		for (int i = 0; i < num.size(); ++i)
		{
			if(visitedTable.find(num[i]) != visitedTable.end()) continue;
			visitedTable.insert(num[i]);
			int curLen = 1;
			int nextNum = num[i]-1;//search left
			while (hashTable.find(nextNum) != hashTable.end())
			{
				visitedTable.insert(nextNum);
				nextNum--;
				curLen++;
			}
			nextNum = num[i]+1;//search right
			while (hashTable.find(nextNum) != hashTable.end())
			{
				visitedTable.insert(nextNum);
				nextNum++;
				curLen++;
			}
			//keep the maxLen updated
			maxLen = max(maxLen, curLen);
		}
		return maxLen;
	}
};

second time

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        unordered_set<int> existTable;
        for(int i = 0; i < num.size(); ++i) existTable.insert(num[i]);
        unordered_set<int> visitedTable;
        int mmax = INT_MIN;
        for(int i = 0; i < num.size(); ++i)
        {
            int curNum = num[i];
            if(visitedTable.find(curNum) != visitedTable.end()) continue;
            int cnt = 1;
            //search left
            int left = curNum;
            while(existTable.find(--left) != existTable.end()) cnt++, visitedTable.insert(left);
            int right = curNum;
            while(existTable.find(++right) != existTable.end()) cnt++, visitedTable.insert(right);
            mmax = max(cnt, mmax);
        }
        return mmax;
    }
};


你可能感兴趣的:([LeetCode]Longest Consecutive Sequence)