[LeetCode] Longest Consecutive Sequence

int longestConsecutive(vector<int> &num) {
    map<int, bool> map;
	for (int i = 0; i < num.size(); i++)
	{
		map[num[i]] = true;
	}
	int maxLen = 0;
	for (int i = 0; i < num.size(); i++)
	{	
		if (map[num[i]] == true)
		{
			int len = 1;
			int left = num[i] - 1;
			while (map.count(left) && map[left] == true)
			{
				map[left] = false;
				len++;
				left--;		
			}
			int right = num[i] + 1;
			while (map.count(right) && map[right] == true)
			{
				map[right] = false;
				len++;
				right++;
			}
			maxLen = len > maxLen? len :maxLen;
		}	
	}
	return maxLen;
}

你可能感兴趣的:(LeetCode,刷题)