
原题链接
代码如下:
import java.util.HashSet;
import java.util.Set;
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> numsSet = new HashSet<Integer>();
for (int num : nums) {
numsSet.add(num);
}
int longestNum = 0;
for (int num : numsSet) {
if (!numsSet.contains(num - 1)) {
int curNum = num;
int curLongest = 1;
while (numsSet.contains(curNum + 1)) {
curNum++;
curLongest++;
}
longestNum = Math.max(longestNum, curLongest);
}
}
return longestNum;
}
public static void main(String[] args) {
Solution a = new Solution();
int[] k = new int[] { 100, 4, 200, 1, 3, 2 };
System.out.println(a.longestConsecutive(k));
}
}