Skip to content

Commit 58bd49b

Browse files
committed
add longest consecutive sequence
1 parent d031f8e commit 58bd49b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
import java.util.HashSet;
3+
import java.util.Set;
4+
/**
5+
๊ฐ ์—ฐ์† ์ˆ˜์—ด์˜ ์‹œ์ž‘์ ์—์„œ๋งŒ ์นด์šดํŒ…ํ•˜๊ธฐ
6+
7+
1. ๋ชจ๋“  ์ˆซ์ž๋ฅผ Set์— ๋„ฃ๊ธฐ
8+
2. ๋ฐฐ์—ด์„ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ํ˜„์žฌ index์— ํ•ด๋‹นํ•˜๋Š” ์ˆซ์ž -1 ๊ฐ’์ด Set์— ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธ
9+
3. ๋งŒ์•ฝ Set์— ๊ฐ’์ด ์กด์žฌํ•œ๋‹ค๋ฉด ์—ฐ์†๋œ ์ˆซ์ž์˜ ์‹œ์ž‘์ง€์ ์ด ์•„๋‹ˆ๋‹ค.
10+
4. ๋งŒ์•ฝ Set์— ๊ฐ’์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ์—ฐ์†๋œ ์ˆซ์ž์˜ ์‹œ์ž‘์ง€์ ์ด๋‹ค.
11+
5. ์‹œ์ž‘์ง€์ ์„ ์ฐพ์•˜์œผ๋ฉด num + 1๊ฐ’์ด ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธ, num+2๊ฐ’์ด ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธํ•˜๋ฉด์„œ ๋“ฑ์žฅํ•˜์ง€ ์•Š์„๋•Œ ๊นŒ์ง€ ์ฒดํฌํ•˜๊ณ  ๊ธธ์ด๋ฅผ ์ตœ๋Œ€ ๊ธธ์ด์™€ ๋น„๊ตํ•œ๋‹ค. (์ด๋•Œ ๋ฐฐ์—ด์„ ๊ธฐ์ค€์œผ๋กœ ํƒ์ƒ‰ํ•˜๋ฉด ๋ฐฐ์—ด์— ์ค‘๋ณต ์ˆซ์ž๊ฐ€ ์žˆ์„๊ฒฝ์šฐ ๋งค๋ฒˆ ์ค‘๋ณต์ˆซ์ž์— ๋Œ€ํ•ด์„œ length๋ฅผ ์ฒดํฌํ•ด์•ผํ•˜๋ฏ€๋กœ Set์ด ์ด๋“์ž„)
12+
*/
13+
class sangyyypark {
14+
public int longestConsecutive(int[] nums) {
15+
Set<Integer> set = new HashSet<>();
16+
for(int i = 0; i < nums.length; i++) {
17+
int num = nums[i];
18+
set.add(num);
19+
}
20+
int max = 0;
21+
22+
for(int num : set) {
23+
if(set.contains(num-1)) {
24+
continue;
25+
}
26+
int index = 1;
27+
int length = 1;
28+
while(set.contains(num+index)) {
29+
index++;
30+
length++;
31+
}
32+
max = Math.max(max,length);
33+
}
34+
return max;
35+
}
36+
}
37+

0 commit comments

Comments
ย (0)