java
/**
* @author wx
* @description 最长子序列
* @create 2023/12/26
**/
public class LongestConsecutive {
public static void main(String[] args) {
int[] arr = new int[]{100, 4, 200, 1, 3, 2};
int result = longestConsecutive(arr);
System.out.println(result);
}
public static int longestConsecutive(int[] nums) {
int result = 0;
Set<Integer> set = new HashSet();
for (int num : nums) set.add(num);
for (int num : nums) {
if (!set.contains(num + 1)) {
int max = 0;
while (set.contains(num--)) {
max++;
}
result = Math.max(result, max);
}
}
return result;
}
}