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

Commit000a7c5

Browse files
author
applewjg
committed
LongestConsecutiveSequence
Change-Id: I969193b628c0b892905721fe32abacbdf5a71481
1 parent81949ac commit000a7c5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎LongestConsecutiveSequence.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jun 18, 2014
4+
Problem: Longest Consecutive Sequence
5+
Difficulty: Hard
6+
Source: https://oj.leetcode.com/problems/longest-consecutive-sequence/
7+
Notes:
8+
Given an unsorted array of integers, find the length of the longest consecutive
9+
elements sequence.
10+
For example,
11+
Given [100, 4, 200, 1, 3, 2],
12+
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
13+
Your algorithm should run in O(n) complexity.
14+
15+
Solution 1: Update solution.
16+
*/
17+
18+
publicclassSolution {
19+
publicintlongestConsecutive(int[]num) {
20+
intsize =num.length;
21+
HashMap<Integer,Integer>unmap =newHashMap<Integer,Integer>();
22+
intres =0;
23+
for (inti =0;i <size; ++i) {
24+
if (unmap.containsKey(num[i]) ==true)continue;
25+
intval =num[i];
26+
if (unmap.containsKey(val -1) ==true &&unmap.containsKey(val +1) ==true) {
27+
unmap.put(val,unmap.get(val -1) +unmap.get(val +1) +1);
28+
unmap.put(val -unmap.get(val -1),unmap.get(val));
29+
unmap.put(val +unmap.get(val +1),unmap.get(val));
30+
}elseif (unmap.containsKey(val -1) ==true) {
31+
unmap.put(val,unmap.get(val -1) +1);
32+
unmap.put(val -unmap.get(val -1),unmap.get(val));
33+
}elseif (unmap.containsKey(val +1) ==true) {
34+
unmap.put(val,unmap.get(val +1) +1);
35+
unmap.put(val +unmap.get(val +1),unmap.get(val));
36+
}else {
37+
unmap.put(val,1);
38+
}
39+
res =Math.max(res,unmap.get(val));
40+
}
41+
returnres;
42+
}
43+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp