Longest Consecutive Sequence

xiaoxiao2021-02-27  366

Longest Consecutive Sequence

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.

解析:

若是连续的序列那么用该序列中任意一个数字都能找到该序列,那么遍历每个元素,找每个元素的序列,并把经过的元素都置为已访问,下次不再遍历这些元素。

代码:

class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_map<int,int>m; for (int i=0; i<nums.size(); i++) { m[nums[i]]=1; } int ans=0; int tempans=0; for (int i=0; i<nums.size(); i++) { tempans=1; if (m.count(nums[i])&&m[nums[i]]) { m[nums[i]]=0; int left=nums[i]-1; while (m.count(left)&&m[left]) { m[left--]=0; tempans++; } int right=nums[i]+1; while(m.count(right)&&m[right]) { m[right++]=0; tempans++; } } if (ans<tempans) { ans=tempans; } } return ans; } };

转载请注明原文地址: https://www.6miu.com/read-1823.html

最新回复(0)