-
Notifications
You must be signed in to change notification settings - Fork 1
/
_0128_Longest_Consecutive_Sequence.java
77 lines (67 loc) · 1.79 KB
/
_0128_Longest_Consecutive_Sequence.java
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
// https://leetcode.com/problems/longest-consecutive-sequence/
// Optimised Solution by Sorted Array => Replacing Heap
import java.util.*;
public class _0128_Longest_Consecutive_Sequence {
public static void main(String[] args) {
int[] nums = {0,3,7,2,5,8,4,6,0,1};
System.out.println(new Solution0128().longestConsecutive_Optimised(nums));
}
}
class Solution0128 {
// NO Extra Space => By Sorting Array
public int longestConsecutive_Optimised(int[] nums)
{
if(nums.length < 2)
{
return nums.length;
}
Arrays.sort(nums);
int max = 1;
int tempMax = 1;
for(int i = 1; i < nums.length; i++)
{
int curr = nums[i];
if(curr == nums[i-1] + 1)
{
tempMax++;
}
else if(nums[i-1] != curr)
{
max = Math.max(max, tempMax);
tempMax = 1;
}
}
return max = Math.max(max, tempMax);
}
// With Extra Space => HEAP
public int longestConsecutive(int[] nums)
{
if(nums.length < 2)
{
return nums.length;
}
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int a : nums)
{
pq.add(a);
}
int max = 1;
int tempMax = 1;
int prev = pq.remove();
while(!pq.isEmpty())
{
int curr = pq.remove();
if(curr == prev + 1)
{
tempMax++;
}
else if(prev != curr)
{
max = Math.max(max, tempMax);
tempMax = 1;
}
prev = curr;
}
return max = Math.max(max, tempMax);
}
}