-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path128. Longest Consecutive Sequence
68 lines (53 loc) · 1.25 KB
/
128. Longest Consecutive Sequence
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
#Better Solution
Runtime 15 ms
Beats 93.34%
Memory 57.4 MB
Beats 50.15%
class Solution {
public int longestConsecutive(int[] nums) {
if(nums.length <=1)
return nums.length;
Arrays.sort(nums);
int ans=1,res=1;
for(int i=1;i<nums.length;i++){
if(nums[i] == nums[i-1]+1){
ans++;
if(ans>res)
res=ans;
}else if(nums[i] == nums[i-1]){}
else{
ans=1;
}
}
return res;
}
}
#Optimal Solution
Runtime 24 ms
Beats 75.31%
Memory 56.6 MB
Beats 67.42%
class Solution {
public int longestConsecutive(int[] a) {
int n = a.length;
if (n == 0)
return 0;
int longest = 1;
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
set.add(a[i]);
}
for (int it : set) {
if (!set.contains(it - 1)) {
int cnt = 1;
int x = it;
while (set.contains(x + 1)) {
x = x + 1;
cnt = cnt + 1;
}
longest = Math.max(longest, cnt);
}
}
return longest;
}
}