File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .HashSet ;
2
+ import java .util .Set ;
3
+
4
+ // ์ฐ์์ ์ธ ์ซ์์ ๊ธธ์ด๋ฅผ ๊ตฌํ๋ ๊ฒ์ด๊ธฐ ๋๋ฌธ์ ์ด์ , ๋ค์ ์๊ฐ ์งํฉ์ ์ผ๋ถ์ธ์ง๋ฅผ ํ์
ํด์ผ ํ๋ค.
5
+ // map, set ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ฉด ์กฐํ ์ฑ๋ฅ์ O(1)๋ก ๋์ผ ์ ์๋ค.
6
+ // ์ด๋ ค์ ๋ ์ ์ ์ฐ์์ ์ธ ์ซ์์ start๊ฐ ๋๋ ์ฌ๋ถ ์กฐ๊ฑด์ ๋ ์ฌ๋ฆฌ๋ ๊ฒ์ด์๋ค. while๋ฌธ์ด ์ฝํด์ length++ํ๋ ๋ก์ง์ด ํ๋ค์๋ค.
7
+ // ๋ฌธ์ ์ ์กฐ๊ฑด์ ๋ฐฐ์ด ๋ด์์์ ์ฐ์์ ์ธ ์ซ์์ ๊ธธ์ด์ด๊ธฐ ๋๋ฌธ์ while์ ์ฌ์ฉํด๋ ์ฑ๋ฅ ์ด์ ๊ฑฑ์ ํ ํ์๊ฐ ์์๋ค.
8
+ class Solution {
9
+ public int longestConsecutive (int [] nums ) {
10
+ Set <Integer > set = new HashSet <>();
11
+
12
+ for (int n : nums ) {
13
+ set .add (n );
14
+ }
15
+
16
+ int maxLength = 0 ;
17
+
18
+ for (int n : nums ) {
19
+ if (!set .contains (n - 1 )) { // ๋ด ์ด์ ์ซ์๊ฐ ์งํฉ์ ์๋ค == ๋ด๊ฐ ์ต์ ์ซ์๋ค.
20
+ int length = 1 ;
21
+
22
+ while (set .contains (n + length )) {
23
+ length ++;
24
+ }
25
+
26
+ maxLength = Math .max (length , maxLength );
27
+ }
28
+ }
29
+
30
+ return maxLength ;
31
+ }
32
+ }
You canโt perform that action at this time.
0 commit comments