128. 最长连续序列
⭐ AC code
class Solution {
public int longestConsecutive(int[] nums)
{
if (nums.length == 0)// 特判为空的数组,返回0
return 0;
// set实现去重
HashSet<Integer> set = new HashSet<>();
for (int x : nums)
set.add(x);
Object[] array = set.toArray();
// 数组复制
Integer[] numbers = Arrays.copyOfRange(array, 0, array.length, Integer[].class);
Arrays.sort(numbers);
int l = 0;
int r = 1;
int ans = 1;
// 双指针
while (r <= numbers.length)
{
if (r == numbers.length)
{
ans = Math.max(ans, r - l);
break;
}
if (numbers[r - 1] + 1 == numbers[r])
r++;
else
{
ans = Math.max(ans, r - l);
l = r++;
}
}
return ans;
}
}