File tree 5 files changed +86
-0
lines changed
longest-consecutive-sequence
5 files changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def containsDuplicate (self , nums : List [int ]) -> bool :
3
+ return len (nums ) != len (set (nums ))
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ class Solution :
4
+ def rob (self , nums : List [int ]) -> int :
5
+ if len (nums ) == 1 :
6
+ return nums [0 ]
7
+
8
+ # prev1: 이전 집까지의 최대 이익
9
+ # prev2: 전전 집까지의 최대 이익
10
+ prev1 , prev2 = 0 , 0
11
+ for num in nums :
12
+ temp = prev1
13
+ prev1 = max (prev2 + num , prev1 ) # 현재 집을 털었을 때와 안 털었을 때 중 더 큰 이익 선택
14
+ prev2 = temp
15
+
16
+ return prev1
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ class Solution :
4
+ def longestConsecutive (self , nums : List [int ]) -> int :
5
+ # Convert to set for O(1) lookups
6
+ num_set = set (nums )
7
+ longest_length = 0
8
+
9
+ for num in num_set :
10
+ # Only start counting if num is the start of a sequence
11
+ if num - 1 not in num_set :
12
+ current_num = num
13
+ current_length = 1
14
+
15
+ # Count the length of the sequence
16
+ while current_num + 1 in num_set :
17
+ current_num += 1
18
+ current_length += 1
19
+
20
+ longest_length = max (longest_length , current_length )
21
+
22
+ return longest_length
Original file line number Diff line number Diff line change
1
+ from collections import Counter
2
+ from typing import List
3
+
4
+ class Solution :
5
+ def topKFrequent (self , nums : List [int ], k : int ) -> List [int ]:
6
+ # 빈도 계산
7
+ count = Counter (nums )
8
+ n = len (nums )
9
+
10
+ # 빈도수를 기준으로 버킷 생성 (0에서 n까지)
11
+ buckets = [[] for _ in range (n + 1 )]
12
+
13
+ # 각 숫자를 해당 빈도수의 버킷에 추가
14
+ for num , freq in count .items ():
15
+ buckets [freq ].append (num )
16
+
17
+ # 빈도가 높은 순서대로 k개의 숫자를 추출
18
+ result = []
19
+ for freq in range (n , 0 , - 1 ):
20
+ if buckets [freq ]:
21
+ result .extend (buckets [freq ])
22
+
23
+ if len (result ) == k :
24
+ return result
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def isPalindrome (self , s : str ) -> bool :
3
+ # two pointer
4
+ left , right = 0 , len (s ) - 1
5
+
6
+ while left < right :
7
+ # compare only alphanumeric characters
8
+ while left < right and not s [left ].isalnum ():
9
+ left += 1
10
+ while left < right and not s [right ].isalnum ():
11
+ right -= 1
12
+
13
+ # compare with lowercase
14
+ if s [left ].lower () != s [right ].lower ():
15
+ return False
16
+
17
+ # move pointers
18
+ left += 1
19
+ right -= 1
20
+
21
+ return True
You can’t perform that action at this time.
0 commit comments