File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Runtime: 26ms
3+ * Time Complexity: O(n)
4+ * - HashSet ꡬμ±: O(n)
5+ * - λͺ¨λ μμ μν: μ΅μ
O(n), νκ· μ μΌλ‘ λ λΉ λ¦ (μ‘°κΈ° μ’
λ£)
6+ * - μ°μ μμ΄ νμ: O(n)
7+ *
8+ * Memory: 95.11MB
9+ * Space Complexity: O(n)
10+ *
11+ * Approach: HashSetμ μ΄μ©νμ¬ μ€λ³΅ μ κ±° ν μ°μ μμ΄ κΈΈμ΄ νμ
12+ * - μ°μ μμ΄μ μμμ λ§ νμνμ¬ μ€λ³΅ μμ
λ°©μ§ (num-1μ΄ μλ κ²½μ°)
13+ * - κ° μμμ μμ μ°μλ λ€μ μ«μλ€μ μμ°¨μ μΌλ‘ νμ
14+ * - nums μ¬μ΄μ¦μ λλ¬ μ μ‘°κΈ° μ’
λ£νμ¬ λΆνμν νμ λ°©μ§
15+ */
16+ class Solution {
17+ public int longestConsecutive (int [] nums ) {
18+ if (nums .length == 0 ) return 0 ;
19+
20+ Set <Integer > set = new HashSet <>();
21+ for (int num : nums ) {
22+ set .add (num );
23+ }
24+
25+ int longestLength = 0 ;
26+ for (int num : set ) {
27+ if (!set .contains (num -1 )) {
28+ int currentNum = num ;
29+ int currentLength = 1 ;
30+
31+ while (set .contains (currentNum +1 )) {
32+ currentNum ++;
33+ currentLength ++;
34+ }
35+
36+ longestLength = longestLength < currentLength ? currentLength : longestLength ;
37+ if (longestLength == set .size ()) {
38+ return longestLength ;
39+ }
40+ }
41+ }
42+
43+ return longestLength ;
44+ }
45+ }
You canβt perform that action at this time.
0 commit comments