首页 > 代码库 > 128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

 1 class Solution { 2 public: 3     int longestConsecutive(vector<int>& nums) { 4         if (nums.size() <= 1) return nums.size(); 5         else { 6             map<int, int> used; 7             for (const auto& item : nums) used[item] = 0; 8             int count = 0, len = 0; 9             for (size_t i = 0; i < nums.size(); ++i) {10                 if (used[nums[i]] == 1) continue;11                 count = 1;12                 for (int j = nums[i] + 1; ; ++j) {13                     if (used.find(j) != used.end() && used[j] == 0) {14                         ++count; used[j] = 1;15                     }16                     else break;17                 }18                 for (int j = nums[i] - 1; ; --j) {19                     if (used.find(j) != used.end() && used[j] == 0) {20                         ++count; used[j] = 1;21                     }22                     else break;23                 }24                 if (count > len) len = count;25             }26             return len;27         }28     }29 };

 

128. Longest Consecutive Sequence