Skip to content

Commit b9037b5

Browse files
committed
add: longest consecutive sequence solution
1 parent 32db53b commit b9037b5

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
/**
3+
* 정렬되지 않은 정수 배열 nums가 주어질 때 가장 긴 연속적인 요소 배열의 길이를 반환
4+
* */
5+
import java.util.Arrays;
6+
public class Solution {
7+
8+
public int longestConsecutive(int[] nums) {
9+
10+
if (nums.length == 0) {
11+
return 0;
12+
}
13+
14+
Arrays.sort(nums);
15+
16+
int maxCnt = 1;
17+
int cnt = 1;
18+
for (int i = 0; i < nums.length - 1; i++) {
19+
if (nums[i] == nums[i + 1]) {
20+
continue;
21+
}
22+
if (nums[i] + 1 == nums[i + 1]) {
23+
cnt++;
24+
} else {
25+
cnt = 1;
26+
}
27+
maxCnt = Math.max(maxCnt, cnt);
28+
}
29+
return maxCnt;
30+
}
31+
32+
}

0 commit comments

Comments
 (0)