0%

leetcode 128 Solution

代码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.demo.s128;

import java.util.HashSet;
import java.util.Set;

/**
* 最长连续序列
* 给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
*
* 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode.cn/problems/longest-consecutive-sequence
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Solution {
public int longestConsecutive(int[] nums) {
//数字集合
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
//最长序列长度
int longestStreak = 0;
//遍历集合
for (int num : num_set) {
//找到最小的数字开始
if (!num_set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
//找更大的数字是否存在,并统计连续数字序列长度
while (num_set.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
//比较最长的序列
longestStreak = Math.max(longestStreak, currentStreak);
}
}

return longestStreak;
}
}