File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -113,4 +113,30 @@ public int longestConsecutive(int[] nums) {
113
113
return max ;
114
114
}
115
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
+ 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
+ }
116
142
}
You can’t perform that action at this time.
0 commit comments