题意:给定一个数组,找出里边的最长连续序列
思路:把数组元素加入Hashset中,然后遍历数组,如果HashSet中有值,那么查看它左右最长连续的序列是否在set中,如果在找出最长的左右序列,并移除在当前序列中的值,根据当前序列长度,更新max
思想:双指针
复杂度:时间O(n),空间O(n)
class Solution {
public int longestConsecutive(int[] nums) {
int len = nums.length;
HashSet<Long> set = new HashSet();
for(int i=0;i<len;i++) {
set.add((long)nums[i]);
}
int max = 0;
for(int i=0;i<len;i++) {
if(set.contains((long)nums[i])){
long temp = (long)nums[i];
int left = 0;
while(set.contains(--temp)){
set.remove(temp);
left++;
}
temp = (long)nums[i];
int right = 0;
while(set.contains(++temp)){
set.remove(temp);
right++;
}
if(max<right+left+1) {
max = right + left + 1;
}
set.remove((long)nums[i]);
}
}
return max;
}
}
网友评论