File tree Expand file tree Collapse file tree 1 file changed +19
-19
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +19
-19
lines changed Original file line number Diff line number Diff line change 1- import java .util .HashSet ;
1+ import java .util .Arrays ;
22
3- class Solution {
4- public int longestConsecutive (int [] nums ) {
5- HashSet <Integer > mySet = new HashSet <Integer >();
6-
7- for (int num : nums ) {
8- mySet .add (num );
9- }
10-
11- int result = 0 ;
12- for (int num : mySet ) {
13- int cnt = 1 ;
14- if (!mySet .contains (num - 1 )) {
15- while (mySet .contains (++num )) {
16- ++cnt ;
17- }
18- result = Math .max (cnt , result );
3+ // 시간 복잡도: O(nlogn) - 정렬
4+ // 공간 복잡도: O(1)
5+ class Solution {
6+ public int longestConsecutive (int [] nums ){
7+ if (nums .length == 0 ) return 0 ;
8+ Arrays .sort (nums );
9+ int pre = nums [0 ];
10+ int max = 1 ;
11+ int count = 1 ;
12+ for (int i = 1 ; i < nums .length ; i ++){
13+ if (nums [i ] == pre + 1 ){
14+ count ++;
15+ max = Math .max (max , count );
16+ } else if (nums [i ] != pre ){
17+ count = 1 ;
1918 }
19+ pre = nums [i ];
2020 }
21- return result ;
21+ return max ;
2222 }
23- }
23+ }
You can’t perform that action at this time.
0 commit comments