标签:
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.
可以AC,但不符合 O(n)的要求
1 class Solution { 2 public: 3 int longestConsecutive(vector<int>& nums) { 4 sort(nums.begin(),nums.end()); 5 6 int cnt=0; 7 int max=0; 8 9 for(int i=1;i<nums.size();i++) 10 { 11 12 if(nums[i]-nums[i-1]==1) 13 cnt++; 14 else if(nums[i]-nums[i-1]>1) 15 { 16 if(max<cnt) 17 max=cnt; 18 cnt=0; 19 } 20 } 21 if(max<cnt) 22 max=cnt; 23 24 return max+1; 25 } 26 };
【leetcode】Longest Consecutive Sequence
标签:
原文地址:http://www.cnblogs.com/jawiezhu/p/4491686.html