Skip to content

Commit e46e795

Browse files
committed
rivkode longest consecutive sequence
1 parent 5e4c592 commit e46e795

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
1. 문제 이해
3+
1씩 증가하는 가장 긴 배열을 구하는 문제
4+
5+
2. 예외 케이스
6+
똑같은 수만 나올 경우? 1이어야 함
7+
모두 아닐 경우 0이어야 함
8+
9+
[1, 2, 3, 5, 7, 7, 7, 8, 9, 10]
10+
1, 2, 3, 0, 0, 0, 0, 1, 2, 3
11+
12+
3. 알고리즘
13+
dp 로 접근 ?
14+
그냥 구현인 것 같기도
15+
아니 일단 정렬을 해야함
16+
아 Arrays.sort() 하면 시간이 nlogn 아닌가 ?
17+
정렬 하고 순차적으로 가다가 끊기면 다시 0으로 초기화 하고 순차적으로 세야하는거 아닌가 ?
18+
19+
20+
a. 정렬
21+
b. for 문 돌면서 이전 값과 1만큼 차이나는지 체크 후 차이나면 cnt 증가 아니면 cnt 를 이전 최댓값과 비교해서 크면 초기화 아니면 그대로
22+
23+
4. 구현
24+
*/
25+
26+
import java.util.*;
27+
28+
class Solution {
29+
public int longestConsecutive(int[] nums) {
30+
Arrays.sort(nums);
31+
32+
int max = 0;
33+
int tmpMax = 0;
34+
boolean isSame = false;
35+
36+
if (nums.length == 1) {
37+
return 1;
38+
}
39+
40+
if (nums.length == 0) {
41+
return 0;
42+
}
43+
44+
for (int i=0; i<nums.length - 1; i++) {
45+
int cur = nums[i];
46+
int next = nums[i+1];
47+
48+
if (Math.abs(next - cur) == 1) {
49+
tmpMax += 1;
50+
} else if ((next - cur) == 0) {
51+
isSame = true;
52+
continue;
53+
} else {
54+
max = Math.max(max, tmpMax);
55+
tmpMax = 0;
56+
}
57+
}
58+
59+
max = Math.max(max, tmpMax);
60+
61+
return max + 1;
62+
}
63+
}

0 commit comments

Comments
 (0)