LeetCode/com/zerroi/leetcode/Three20/LongestConsecutive.java

40 lines
1.0 KiB
Java
Raw Normal View History

2024-03-21 19:03:41 +08:00
package com.zerroi.leetcode.Three20;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class LongestConsecutive {
public static void main(String[] args) {
SolutionThird solutionThird = new SolutionThird();
int res = solutionThird.longestConsecutive(new int[]{0,3,7,2,5,8,4,6,0,1});
System.out.println("res = " + res);
}
}
class SolutionThird {
public int longestConsecutive(int[] nums) {
if (nums.length == 0) return 0;
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int longest = 0;
for (int num : nums) {
if (!set.contains(num - 1)) {
int currentNum = num;
int currentLength = 1;
while (set.contains(currentNum + 1)) {
currentNum++;
currentLength++;
}
longest = Math.max(longest, currentLength);
}
}
return longest;
}
}