Skip to content

Commit f580fba

Browse files
committed
longest consecutive sequence
1 parent 808c2c0 commit f580fba

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed
Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
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+
}

0 commit comments

Comments
 (0)