首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。