Skip to content

Commit c01a866

Browse files
committed
added test
1 parent 9980969 commit c01a866

File tree

1 file changed

+26
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+26
-0
lines changed

src/main/java/com/fishercoder/solutions/_128.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,4 +113,30 @@ public int longestConsecutive(int[] nums) {
113113
return max;
114114
}
115115
}
116+
117+
public static class Solution3 {
118+
public int longestConsecutive(int[] nums) {
119+
HashSet<Integer> set = new HashSet<>();
120+
for (int i = 0; i < nums.length; i++) {
121+
set.add(nums[i]);
122+
}
123+
int max = 0;
124+
for (int i = 0; i < nums.length; i++) {
125+
int num = nums[i];
126+
/*
127+
我们只考虑从序列最小的数开始即可。
128+
实现的话,当考虑 n 的时候,我们先看一看 n - 1 是否存在,如果不存在,那么从 n 开始就是我们需要考虑的序列了。
129+
否则的话,直接跳过。*/
130+
if (!set.contains(num - 1)) {
131+
int count = 0;
132+
while (set.contains(num)) {
133+
count++;
134+
num += 1;
135+
}
136+
max = Math.max(max, count);
137+
}
138+
}
139+
return max;
140+
}
141+
}
116142
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy