Skip to content

Commit 2be2d1a

Browse files
committed
ok
1 parent 4e57c5f commit 2be2d1a

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

src/com/leetcode/Main128.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.leetcode;
2+
3+
import java.util.Arrays;
4+
import java.util.HashSet;
5+
import java.util.Scanner;
6+
import java.util.Set;
7+
8+
/**
9+
* 128. 最长连续序列
10+
*
11+
* 给定一个未排序的整数数组,找出最长连续序列的长度。
12+
*
13+
* 要求算法的时间复杂度为 O(n)。
14+
*
15+
* 示例:
16+
*
17+
* 输入: [100, 4, 200, 1, 3, 2]
18+
* 输出: 4
19+
* 解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
20+
*
21+
*/
22+
public class Main128 {
23+
public int longestConsecutive(int[] nums) {
24+
if (nums == null || nums.length == 0)
25+
return 0;
26+
Set<Integer> set = new HashSet<>();
27+
for(int num: nums) {
28+
set.add(num);
29+
}
30+
int res = 0;
31+
for (int num: set) {
32+
if (!set.contains(num-1)) {
33+
int curRes = 1;
34+
int curNum = num;
35+
while (set.contains(curNum+1)) {
36+
curRes += 1;
37+
curNum += 1;
38+
}
39+
res = Math.max(res, curRes);
40+
}
41+
}
42+
return res;
43+
}
44+
45+
public static void main(String[] args) {
46+
Main128 m = new Main128();
47+
Scanner sc = new Scanner(System.in);
48+
while (sc.hasNextLine()) {
49+
String line = sc.nextLine();
50+
String[] lineArr = line.split(" ");
51+
int[] nums = new int[lineArr.length];
52+
for (int i = 0; i < lineArr.length; i++) {
53+
nums[i] = Integer.parseInt(lineArr[i]);
54+
}
55+
System.out.println(m.longestConsecutive(nums));
56+
}
57+
58+
}
59+
}

0 commit comments

Comments
 (0)