We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 9980969 commit c01a866Copy full SHA for c01a866
src/main/java/com/fishercoder/solutions/_128.java
@@ -113,4 +113,30 @@ public int longestConsecutive(int[] nums) {
113
return max;
114
}
115
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
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
142
0 commit comments