class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int maxLen = 0;
for (int num : nums) {
if (!set.contains(num - 1)) {
int curLen = 1;
while (set.contains(++num)) {
curLen++;
}
if (curLen > maxLen) {
maxLen = curLen;
}
}
}
return maxLen;
}
}
class Uf {
Map<Integer, Integer> map = new HashMap<>();
public Uf(int[] nums) {
for (int num : nums) {
map.put(num, num);
}
}
int find(int x) {
if (map.get(x) == x) {
return x;
}
map.put(x, find(map.get(x)));
return map.get(x);
}
void union(int x, int y) {
if(map.containsKey(y))
map.put(x, y);
}
}
class Solution {
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
Uf uf = new Uf(nums);
for (int num : nums) {
uf.union(num, num + 1);
}
int maxLen = 1;
for (int num : nums) {
maxLen = Math.max(maxLen, uf.find(num) - num + 1);
}
return maxLen;
}
}