File tree Expand file tree Collapse file tree 1 file changed +18
-20
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +18
-20
lines changed Original file line number Diff line number Diff line change 1- import java .util .* ;
1+ import java .util .Arrays ;
22
33class Solution {
44 public int longestConsecutive (int [] nums ) {
5- // μ€λ³΅ μ κ±° ν μ€λ¦μ°¨μ μ λ ¬
6- Set <Integer > distinct = new HashSet <>();
7- for (int num : nums ) {
8- distinct .add (num );
5+ if (nums .length == 0 ) {
6+ return 0 ;
97 }
10- List <Integer > list = new ArrayList <>(distinct );
11- Collections .sort (list );
128
13- // μ°μλ μ«μλΌλ©΄ μ€νμ μ μ₯
14- Stack <Integer > stack = new Stack <>();
15- int answer = 0 ;
16- for (int num : list ) {
17- if (stack .isEmpty ()) {
18- stack .add (num );
9+ Arrays .sort (nums );
10+
11+ int answer = 1 ;
12+ int current = 1 ;
13+ for (int i =1 ; i <nums .length ; i ++) {
14+ // μ΄μ μ«μμ κ°λ€λ©΄ μ€ν΅
15+ if (nums [i -1 ] == nums [i ]) {
1916 continue ;
2017 }
2118
22- // μ°μλ μ«μκ° μλλΌλ©΄ νμ¬κΉμ§ μ°μλ μλ₯Ό μ μ₯ ν μ€ν μ΄κΈ°ν
23- if (stack .peek () + 1 != num ) {
24- answer = Math .max (answer , stack .size ());
25- stack .clear ();
26- }
19+ // μ°μλ μ«μλΌλ©΄ μ¦κ°, μλλΌλ©΄ μ΄κΈ°ν
20+ if (nums [i -1 ] + 1 == nums [i ]) {
21+ current ++;
22+ answer = Math .max (answer , current );
2723
28- stack .add (num );
24+ } else {
25+ current = 1 ;
26+ }
2927 }
3028
31- return Math . max ( answer , stack . size ()) ;
29+ return answer ;
3230 }
3331}
You canβt perform that action at this time.
0 commit comments