-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashmaps:Longest consecutive Sequence
65 lines (54 loc) · 1.86 KB
/
Hashmaps: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
import java.util.HashMap;
import java.util.ArrayList;
public class Solution {
public static ArrayList<Integer> longestConsecutiveIncreasingSequence(int[] arr) {
HashMap<Integer,Boolean> map = new HashMap<>();
ArrayList<Integer> output = new ArrayList<>();
for(int i=0;i<arr.length;i++){
map.put(arr[i],true);
}
int maxlength = 0;
int start = 0;
for(int i=0;i<arr.length;i++){
if(map.get(arr[i])){
int length = 0;
int temp = arr[i];
while(map.containsKey(temp)){
length++;
map.put(temp,false);
temp = temp+1;
}
int starttemp = arr[i];
temp = arr[i]-1;
while(map.containsKey(temp)){
length++;
map.put(temp,false);
starttemp = temp;
temp = temp-1;
}
if(length > maxlength){
maxlength = length;
start = starttemp;
}else if(length == maxlength){
maxlength = length;
//start = 10 starttemp = 4
for(int j=0;j<arr.length;j++){
if(arr[j] == start){
start = start;
break;
}else if(arr[j] == starttemp){
start = starttemp;
break;
}
}
}
}
// else{
// continue;
// }
}
for(int i = start;i<start+maxlength;i++){
output.add(i);
}
return output;
}