-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcm_p0128_longest_consecutive_sequence.java
More file actions
89 lines (66 loc) · 1.79 KB
/
lcm_p0128_longest_consecutive_sequence.java
File metadata and controls
89 lines (66 loc) · 1.79 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
LCM 128. Longest Consecutive Sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Constraints:
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Topics:
- Array
- Hash Table
- Union Find
*/
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
class Solution {
// Time Complexity: O(n) - 1105 ms -> 19.98%
// Space Complexity: O(n) - 66.0 MB -> 53.50%
public int longestConsecutive(int[] nums) {
int maxLength = 0;
int currLength = 0;
Set<Integer> set = new HashSet<>();
for (int num : nums) set.add(num);
for (int num : nums) {
// process only starting numbers
if (!set.contains(num - 1)) {
currLength = 0;
while (set.contains(num++)) {
currLength++;
}
maxLength = Math.max(currLength, maxLength);
}
}
return maxLength;
}
// Time Complexity: O(n log n) - 16 ms -> 91.59%
// Space Complexity: O(1) - 56.8 MB -> 81.76%
public int longestConsecutiveAlt(int[] nums) {
int n = nums.length;
if (n == 0 || n == 1) {
return n;
}
int maxLength = 1;
int currLength = 1;
Arrays.sort(nums);
int prevNum = nums[0];
for (int i = 1; i < n; i++) {
// check for consecutive numbers
if (nums[i] == prevNum + 1) {
currLength++;
}
// check if curr num is not a dupe of the prev num
else if (nums[i] != prevNum) {
currLength = 1;
}
prevNum = nums[i];
maxLength = Math.max(currLength, maxLength);
}
return maxLength;
}
}
/*
methods:
1. hash set - process only the starting numbers, then build the sequences
2. sorting - check all possible sequences
*/