文章目录
- 题目介绍
- 题解
题目介绍
题解
代码如下:
class Solution {public int longestConsecutive(int[] nums) {int ans = 0;Set<Integer> st = new HashSet<>();for (int num : nums) {st.add(num); // 把 nums元素全部放入哈希集合中}for (int x : st) { // 遍历哈希集合if (st.contains(x - 1)) {continue;}// x 是序列的起点int y = x + 1;while (st.contains(y)) { // 不断查找下一个数是否在哈希集合中y++;}// 循环结束后,y-1 是最后一个在哈希集合中的数ans = Math.max(ans, y - x); // 从 x 到 y-1 一共 y-x 个数}return ans;}
}