File tree Expand file tree Collapse file tree 4 files changed +81
-52
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 4 files changed +81
-52
lines changed Original file line number Diff line number Diff line change 1- from typing import List
2-
3-
41class Solution :
52 def rob (self , nums : List [int ]) -> int :
6- house_length = len (nums )
3+ # 예외 처리: 집이 2개 이하일 경우 그 중 큰 값이 최대 도둑질 금액
4+ if len (nums ) < 3 :
5+ return max (nums )
6+
7+ # DP(Dynamic Programming)를 위한 메모이제이션 배열
8+ # memo[0]: 첫 번째 집까지 고려했을 때 최대 도둑질 금액
9+ # memo[1]: 두 번째 집까지 고려했을 때 최대 도둑질 금액
10+ memo = [nums [0 ], max (nums [0 ], nums [1 ])]
711
8- if house_length == 0 :
9- return 0
10- if house_length == 1 :
11- return nums [ 0 ]
12- if house_length == 2 :
13- return max ( nums [0 ], nums [ 1 ])
12+ # 세 번째 집부터 순차적으로 도둑질 시나리오 검토
13+ # 매 집마다 두 가지 선택이 있음: 현재 집을 털거나 vs 털지 않거나
14+ for num in nums [ 2 :] :
15+ # 현재 집을 털 경우: 현재 집 금액 + 전전 집까지의 최대 금액
16+ # (인접한 집은 털 수 없으므로 바로 이전 집은 건너뜀)
17+ robbed = memo [0 ] + num
1418
15- dp = [nums [0 ], max (nums [0 ], nums [1 ])]
19+ # 현재 집을 털지 않는 경우: 이전 집까지의 최대 금액을 그대로 유지
20+ not_robbed = memo [1 ]
1621
17- for index in range (2 , house_length ):
18- dp .append (max (dp [index - 1 ], dp [index - 2 ] + nums [index ]))
22+ # 메모이제이션 배열 업데이트
23+ # 다음 반복을 위해 memo[0]은 이전까지의 최대값으로 갱신
24+ memo [0 ] = memo [1 ]
25+ # memo[1]은 현재까지의 최대값(현재 집을 털거나 안 털거나 중 더 큰 값)으로 갱신
26+ memo [1 ] = max (robbed , not_robbed )
1927
20- return dp [- 1 ]
28+ # 마지막 집까지 고려했을 때의 최대 도둑질 금액 반환
29+ return memo [1 ]
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 1+ from typing import List
2+
3+
4+ class Solution :
5+ def longestConsecutive (self , nums : List [int ]) -> int :
6+ # Time Complexity: O(n) where n is the length of nums
7+ # Strategy: Use a set for O(1) lookups and only extend sequences from their starting points
8+ if not nums :
9+ return 0
10+
11+ max_streak = 0
12+ num_set = set (nums )
13+
14+ # Only check sequences from their starting points to avoid redundant work
15+ for num in num_set :
16+ current_streak = 0
17+
18+ # Check if this number is the start of a sequence (no left neighbor)
19+ if num - 1 not in num_set :
20+ # Found a sequence start - extend it as far as possible
21+ current_num = num
22+
23+ while current_num in num_set :
24+ current_streak += 1
25+ current_num += 1
26+
27+ # Update the longest streak found so far
28+ max_streak = max (max_streak , current_streak )
29+
30+ return max_streak
Original file line number Diff line number Diff line change 1+ from collections import Counter
2+
3+
4+ def top_k_frequent (nums , k ):
5+ # Count the frequency of each number in the input list
6+ counter = Counter (nums )
7+
8+ # Find the maximum frequency among all numbers
9+ max_freq = max (counter .values ())
10+
11+ # Create a list of empty lists (buckets) where index represents frequency
12+ buckets = [[] for _ in range (max_freq + 1 )]
13+
14+ # Place each number into the bucket corresponding to its frequency
15+ for num , freq in counter .items ():
16+ buckets [freq ].append (num )
17+
18+ # Initialize an empty list to store the result
19+ result = []
20+
21+ # Iterate over the buckets in reverse order (from highest frequency to lowest)
22+ for freq in range (max_freq , 0 , - 1 ):
23+ # Add all numbers in the current bucket to the result
24+ result .extend (buckets [freq ])
25+
26+ # If we have collected at least k elements, return the first k elements
27+ if len (result ) >= k :
28+ return result [:k ]
You can’t perform that action at this time.
0 commit comments