Longest Consecutive Sequence LeetCode solution in Java

1
class Solution {
2
public int longestConsecutive(int[] nums) {
3
Set<Integer> storage = new HashSet();
4

5
for (int i = 0; i < nums.length; i++) {
6
storage.add(nums[i]);
7
}
8

9
int maxL = 0;
10

11
for (int i = 0; i < nums.length; i++) {
12

13
// check if nums[i] id present in set or not
14
// since after checking in set we remove the element from
15
// set, there is no double calculation for same sequence
16
if (storage.contains(nums[i])) {
17
storage.remove(nums[i]);
18

19
int dec = nums[i] - 1;
20
int inc = nums[i] + 1;
21
int tempL = 1;
22

23
// check both ways from nums[i] and calculate
24
// tempL. since we are removing elements from
25
// set we only calculate once for every sequence.
26

27
while (storage.contains(dec)) {
28
storage.remove(dec);
29
dec--;
30
tempL++;
31
}
32

33
while (storage.contains(inc)) {
34
storage.remove(inc);
35
inc++;
36
tempL++;
37
}
38

39
maxL = Math.max(maxL, tempL);
40
}
41
}
42

43
return maxL;
44
}
45
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0