Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf9435b5

Browse files
committed
long
1 parent46ee550 commitf9435b5

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎hash/LongestConsecutive.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
packageAlgorithms.hash;
2+
3+
importjava.util.HashMap;
4+
5+
publicclassLongestConsecutive {
6+
publicintlongestConsecutive(int[]num) {
7+
if (num ==null) {
8+
return0;
9+
}
10+
11+
HashMap<Integer,Integer>map =newHashMap<Integer,Integer>();
12+
13+
intmax =0;
14+
15+
intlen =num.length;
16+
for (inti =0;i <len ;i++) {
17+
// 寻找以num[i] 起头或是结尾的,如果找到,则可以跳过,因为我们
18+
// 不需要重复的数字
19+
if (map.get(num[i]) !=null) {
20+
continue;
21+
}
22+
23+
intleft =num[i];
24+
intright =num[i];
25+
26+
// 寻找左边界
27+
Integerboard =map.get(num[i] -1);
28+
if (board !=null &&board <left) {
29+
// 更新左边界
30+
left =board;
31+
32+
// 删除左边2个集合
33+
map.remove(left);
34+
map.remove(num[i] -1);
35+
}
36+
37+
// 寻找右边界
38+
board =map.get(num[i] +1);
39+
if (board !=null &&board >right) {
40+
// 更新右边界
41+
right =board;
42+
43+
// 删除右边2个集合
44+
map.remove(right);
45+
map.remove(num[i] +1);
46+
}
47+
48+
// 创建新的合并之后的集合
49+
map.put(left,right);
50+
map.put(right,left);
51+
52+
max =Math.max(max,right -left +1);
53+
}
54+
55+
returnmax;
56+
}
57+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp