-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT23_again.java
More file actions
46 lines (41 loc) · 1.17 KB
/
T23_again.java
File metadata and controls
46 lines (41 loc) · 1.17 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
import java.util.HashSet;
/**
* @Author:Aliyang
* @Data: Created in 下午2:16 18-7-15
* longest-consecutive-sequence:二刷
**/
public class T23_again {
public int longestConsecutive(int[] num) {
if (num==null||num.length==0)
return 0;
int maxLen=0;
HashSet<Integer> set=new HashSet();//保存所有的数字
for (Integer a:num)
set.add(a);
int count=1;
for (Integer a:num){
if (set.contains(a)){
int left=a-1,right=a+1;
while (set.contains(left)){
set.remove(left);
left--;
count++;
}
while (set.contains(right)){
set.remove(right);
right++;
count++;
}
maxLen=count>maxLen?count:maxLen;
if (set.size()!=0)
count=1;
}
}
return maxLen;
}
public static void main(String[] args){
T23_again t=new T23_again();
int[] num={100,4,200,1,3,2};
System.out.println(t.longestConsecutive(num));
}
}