leetcode 128. 最长连续序列
知识点:Set的使用
解题思路:很直观的想法就是直接开一个数组,用下标来表示数,但是数组开不到10的9次方那么大,因此改用set
注意的点:
注意特殊的样例,没说数组一定非空
1,定义set
Set<Integer>num_set=new HashSet<Integer>();
2,在set中添加数
num_set.add(nums[i]);
3,遍历set
for(int num:num_set)
4,查看是否包含,contian要加s
num_set.contains(num+1)
完整代码
class Solution {
public int longestConsecutive(int[] nums) {
if(nums.length==0)return 0;
Set<Integer>num_set=new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
num_set.add(nums[i]);
}
int ans=1;
for(int num:num_set){
int bans=1;
if(!num_set.contains(num-1)){
while(num_set.contains(num+1)){
bans++;
num++;
}
}
ans=Math.max(ans,bans);
}
return ans;
}
}