File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ class Solution {
4+ public int longestConsecutive (int [] nums ) {
5+ // ์ค๋ณต ์ ๊ฑฐ ํ ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
6+ Set <Integer > distinct = new HashSet <>();
7+ for (int num : nums ) {
8+ distinct .add (num );
9+ }
10+ List <Integer > list = new ArrayList <>(distinct );
11+ Collections .sort (list );
12+
13+ // ์ฐ์๋ ์ซ์๋ผ๋ฉด ์คํ์ ์ ์ฅ
14+ Stack <Integer > stack = new Stack <>();
15+ int answer = 0 ;
16+ for (int num : list ) {
17+ if (stack .isEmpty ()) {
18+ stack .add (num );
19+ continue ;
20+ }
21+
22+ // ์ฐ์๋ ์ซ์๊ฐ ์๋๋ผ๋ฉด ํ์ฌ๊น์ง ์ฐ์๋ ์๋ฅผ ์ ์ฅ ํ ์คํ ์ด๊ธฐํ
23+ if (stack .peek () + 1 != num ) {
24+ answer = Math .max (answer , stack .size ());
25+ stack .clear ();
26+ }
27+
28+ stack .add (num );
29+ }
30+
31+ return Math .max (answer , stack .size ());
32+ }
33+ }
You canโt perform that action at this time.
0 commit comments