Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions contains-duplicate/wozlsla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) > len(set(nums))
64 changes: 64 additions & 0 deletions longest-consecutive-sequence/wozlsla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:

# Edge case
if not nums:
return 0

# 1. HashSet
table = set(nums)

logest_seq = 0

# 2. 연속 시퀀스의 시작점 탐색
for num in table:
if (num - 1) not in table: # !!
current_num = num
seq = 1

# 시퀀스 확장
while (current_num + 1) in table:
current_num += 1
seq += 1

# 시퀀스 길이 업데이트
logest_seq = max(logest_seq, seq)

return logest_seq


"""
Time complexity : O(N)
- step 1 (iteration) : O(N)
- 모든 숫자를 해시셋(set)에 저장
- 해시셋 사용 이유 : 중복을 제거하고 O(1) 탐색 가능
- 요소의 추가, 삭제, 존재 여부 확인에 평균적으로 O(1) 시간이 걸리는 자료구조
- 이 성질 덕분에 하단의 풀이가 간단해질 수 있음
- step 2 (iteration) : O(N)
- 각 요소는 for, while 에서 최대 두번 처리됨

Space Complexity)
- 해시셋(딕셔너리): O(N) (최악의 경우, 모든 숫자가 고유할 때)
"""


""" 첫번째 풀이
- 시간복잡도 고려 X. O(NlogN)
- Edge case 대응 필요
- 연속된 요소 시퀀스가 하나가 아닐 경우 고려 필요

class Solution:
def longestConsecutive(self, nums: List[int]) -> int:

nums.sort() # 오름차순

cnt = 1
tmp = nums[0]

for i in range(1, len(nums)):
if nums[i] == tmp + 1:
cnt += 1
tmp = nums[i]

return cnt
"""
49 changes: 49 additions & 0 deletions top-k-frequent-elements/wozlsla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import heapq


class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:

table = {} # 1. Initialize

# 2. Populate frequency map
for i in range(len(nums)):
table[nums[i]] = table.get(nums[i], 0) + 1

# 3. Find top K frequent elements
topk = heapq.nlargest(k, table, key=table.get)
return topk


"""
* 초기 아이디어 *
- 하나씩 전부 돌면서 빈도수 저장, k개 만큼만 -> 비교/정렬 과정 고려 필요
- count 함수를 써서 비교후 저장 -> 더 많은 반복? O
- 일단 한번은 다 돌아야함. 가장 적게 돌 수 있는 방법?
- 전체 순차 비교?
- Counter, 빈도수 + top K개

Time complexity : O(N + MlogK)
- step 2 (iteration) : O(N)
- 리스트의 길이가 N 일때, nums 모두 순회
- step 3 (iteration) : O(NlogK)
- heapq.nlargest 함수는 table의 모든 M개의 요소(키-값 쌍)를 순회하며, 크기 k의 최소 힙을 유지
- 힙에 삽입(or 제거 후 삽입) 연산은 힙의 크기 k에 비례, O(logK)
- 각 요소에 적용 O(MlogK), 최악의 경우 O(NlogK). M은 N을 초과할 수 없음.

Space Complexity)
- 빈도수 맵 (딕셔너리): O(N) (최악의 경우, 모든 숫자가 고유할 때)
- 힙 (heapq.nlargest 내부에서 사용): O(K)

* heapq.nlargest *
- 가장 큰 k개의 요소를 찾는 함수
1. 힙 초기화. 크기가 k인 (최소)힙 생성
2. 순회 및 힙 관리
- table 전체를 순회하며 key=table.get 값을 기준으로 비교
- 힙이 k개 미만일 경우 요소 추가, 다 찼을경우 비교후 재정렬
- 현재 요소 b의 값과 힙의 루트에 있는 요소 a를 비교
- b > a 이면, a를 제거하고 b를 추가 및 재정렬
- b <= a 이면, b를 버림
- 힙에 있는 요소들을 정렬된 리스트로 반환
- max heap이 아닌 min heap을 사용하는 이유
"""
9 changes: 9 additions & 0 deletions two-sum/wozlsla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# idx를 따로 저장해두는 게 좋을까? X -> i를 사용하면 될듯
# 만약, 거꾸로 계산한다면?

for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]