forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsangyyypark.java
More file actions
37 lines (33 loc) ยท 1.37 KB
/
sangyyypark.java
File metadata and controls
37 lines (33 loc) ยท 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.HashSet;
import java.util.Set;
/**
๊ฐ ์ฐ์ ์์ด์ ์์์ ์์๋ง ์นด์ดํ
ํ๊ธฐ
1. ๋ชจ๋ ์ซ์๋ฅผ Set์ ๋ฃ๊ธฐ
2. ๋ฐฐ์ด์ ํ์ํ๋ฉด์ ํ์ฌ index์ ํด๋นํ๋ ์ซ์ -1 ๊ฐ์ด Set์ ์กด์ฌํ๋์ง ํ์ธ
3. ๋ง์ฝ Set์ ๊ฐ์ด ์กด์ฌํ๋ค๋ฉด ์ฐ์๋ ์ซ์์ ์์์ง์ ์ด ์๋๋ค.
4. ๋ง์ฝ Set์ ๊ฐ์ด ์กด์ฌํ์ง ์๋๋ค๋ฉด ์ฐ์๋ ์ซ์์ ์์์ง์ ์ด๋ค.
5. ์์์ง์ ์ ์ฐพ์์ผ๋ฉด num + 1๊ฐ์ด ์กด์ฌํ๋์ง ํ์ธ, num+2๊ฐ์ด ์กด์ฌํ๋์ง ํ์ธํ๋ฉด์ ๋ฑ์ฅํ์ง ์์๋ ๊น์ง ์ฒดํฌํ๊ณ ๊ธธ์ด๋ฅผ ์ต๋ ๊ธธ์ด์ ๋น๊ตํ๋ค. (์ด๋ ๋ฐฐ์ด์ ๊ธฐ์ค์ผ๋ก ํ์ํ๋ฉด ๋ฐฐ์ด์ ์ค๋ณต ์ซ์๊ฐ ์์๊ฒฝ์ฐ ๋งค๋ฒ ์ค๋ณต์ซ์์ ๋ํด์ length๋ฅผ ์ฒดํฌํด์ผํ๋ฏ๋ก Set์ด ์ด๋์)
*/
class sangyyypark {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int i = 0; i < nums.length; i++) {
int num = nums[i];
set.add(num);
}
int max = 0;
for(int num : set) {
if(set.contains(num-1)) {
continue;
}
int index = 1;
int length = 1;
while(set.contains(num+index)) {
index++;
length++;
}
max = Math.max(max,length);
}
return max;
}
}