本文主要是介绍LeetCode-128 最长连续序列,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int length = nums.length;
for(int i=0;i<length;i++)
set.add(nums[i]);
int maxConsecutive = 0;
int nowConsecutive = 0;
for(int num:set){ // set 去重可以快很多
if(set.contains(num - 1))
continue;
else
{
nowConsecutive = 1;
int add = 1;
while(set.contains(num + add)){
nowConsecutive += 1;
add += 1;
}
maxConsecutive = Math.max(maxConsecutive,nowConsecutive);
}
}
return maxConsecutive;
}
}
这篇关于LeetCode-128 最长连续序列的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!