longest-consecutive-sequence leetcode C++

mac2022-06-30  99

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example, Given[100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.

Your algorithm should run in O(n) complexity.

C++

class Solution { public: int longestConsecutive(vector<int>& nums) { int len = nums.size(); unordered_set<int> se; for(int i=0;i<len;i++) se.insert(nums[i]); int maxLen = 0; for(int i=0;i<len;i++){ int tmpLen = 1; for(int tmp = nums[i] + 1;se.count(tmp);tmpLen++,tmp++) se.erase(tmp); for(int tmp = nums[i] - 1;se.count(tmp);tmpLen++,tmp--) se.erase(tmp); maxLen = max(tmpLen, maxLen); } return maxLen; } };

 

转载于:https://www.cnblogs.com/vercont/p/10210276.html

最新回复(0)