题目描述:
给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
示例:
输入:nums = [100,4,200,1,3,2] 输出:4
基础知识:
mp[t]++ 为map中的value值(且设置value值为int)
for(auto t:nums) 遍历数组nums,将每一个字符元素分别赋予t,即对数组内的每个字符中的每个元素进行遍历
if/while(map[t-1]) 为判断map[t-1]这个值是否存在,存在才继续
代码运行:
#include<unordered_map>
using namespace std;
class Solution{
public:
int longestconsecutive(vector<int>&nums){
unordered_map<int,int>mp;
for(auto t:nums){
mp[t]++;
}
int res=0;
for(auto t:nums){
if(mp[t-1])contine;
int len=1;
while(mp[++t])
len++;
res=max(res,len);//取每一次的最大序列
}
return res;
}
};