将各个连续段长度获取出来,输出最大值即可
最长的连续元素序列长度
https://www.nowcoder.com/practice/57d83a2501164168841c158a7535b458
#include <algorithm> #include <climits> class Solution { public: /** * * @param num int整型vector * @return int整型 */ int longestConsecutive(vector<int>& num) { // write code here sort(num.begin(),num.end()); vector<int> arr; int count=1; int n=num.size(); for(int i=1;i<n;i++){ if(num[i]==num[i-1]+1){ count++; } else if(num[i]-num[i-1]>1){ arr.push_back(count); count=1; } } arr.push_back(count); return *max_element(arr.begin(),arr.end()); } };