-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongstack.java
More file actions
39 lines (36 loc) · 1 KB
/
longstack.java
File metadata and controls
39 lines (36 loc) · 1 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
import java.util.HashSet;
import java.util.Set;
public class longstack {
public static int longestConsecutive(int[] nums){
Set<Integer> num_set = new HashSet<Integer>();
for(int num : nums){
num_set.add(num);
}
int longstack;
int currentnumber;
int maxlongstack=0;
// System.out.println(555);
for(int num : num_set){
System.out.println(num);
if(!num_set.contains(num-1)){//确定当前是最小的数;
longstack=1;
currentnumber=num;
// System.out.println(currentnumber);
while(num_set.contains(currentnumber+1)){
longstack+=1;
currentnumber+=1;
}
maxlongstack=Math.max(longstack,maxlongstack);
}
//o(n) times;
// traversal the array
//hashset can reduce o(times) to 1;
}
return maxlongstack;
}
public static void main(String[] args){
int[] y= new int[]{1,2,4,6,3};
int t=longstack.longestConsecutive(y);
System.out.println(t);
}
}