#Leetcode# 128. Longest Consecutive Sequence
https://leetcode.com/problems/longest-consecutive-sequence/
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, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
代码:
class Solution { public: int longestConsecutive(vector<int>& nums) { if(nums.empty()) return 0; sort(nums.begin(), nums.end()); set<int> s; int n = nums.size(); if(n == 1) return 1; int ans = 1; for(int i = 0; i < n; i ++) { int temp = i; while(temp < n - 1 && (nums[temp] == nums[temp + 1] || nums[temp] + 1 == nums[temp + 1])) { s.insert(nums[temp]); temp ++; } s.insert(nums[temp]); ans = max(ans, (int)s.size()); s.clear(); i = temp; } return ans; } };
盒盒盒盒盒盒盒盒盒盒盒盒~ 两天了啊 终于过了 原来我离答案那么近 也太开心了吧