Skip to content
Closed
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
33 changes: 33 additions & 0 deletions contains-duplicate/hypoxisaurea.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

'''
풀이:
배열 nums 에 중복된 값이 있는지 효율적으로 검사하기 위해 해시 집합(Hash Set) 사용

빈 집합 num_set
배열의 각 요소 num을 순회하며:
만약 num이 이미 num_set에 들어있다면 → 중복이므로 즉시 True 반환
아니라면 num_set에 num을 추가하고 다음 요소로 넘어감
순회를 모두 마쳤음에도 중복을 발견하지 못했다면 False 반환

시간 복잡도: O(n)
배열을 한 번 순회하며, 각 요소마다 집합에 대한 조회(in)와 삽입(add) 연산 수행
파이썬 set의 평균 조회·삽입 비용은 O(1)이므로 전체 O(n)

공간 복잡도: O(n)
최악의 경우 배열의 모든 요소가 중복 없이 집합에 저장되므로, 추가로 n개의 공간을 사용
'''


from typing import List

class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
num_set = set()

for num in nums:
if num in num_set:
return True
else:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

else를 사용하지 않고 바로 num_set.add(num)을 작성해도 좋을 것 같습니다.

num_set.add(num)

return False
40 changes: 40 additions & 0 deletions top-k-frequent-elements/hypoxisaurea.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'''
Bucket Sort 접근:
1. Counter로 각 숫자의 빈도를 계산한다.
2. 빈도 수를 인덱스로 하는 버킷(buckets)을 생성한다.
- buckets[i]에는 등장 횟수가 i번인 숫자들이 들어간다.
3. 버킷의 가장 높은 빈도 인덱스부터 역순으로 순회하며
숫자를 하나씩 결과 리스트(result)에 추가한다.
4. 결과 리스트에 k개가 모이면 반환한다.

시간 복잡도: O(n)
- 빈도 계산 O(n)
- 버킷 채우기 O(n)
- 결과 수집 O(n)

공간 복잡도: O(n)
- Counter 딕셔너리와 버킷 리스트 사용
'''


from typing import List
from collections import Counter


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

buckets = [[] for _ in range(len(nums) + 1)]
for num, count in freq.items():
buckets[count].append(num)

result = []
for i in range(len(buckets) - 1, 0, -1):
for num in buckets[i]:
result.append(num)

if len(result) == k:
return result

return result
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

세개의 모든 파일 린트에러로 VS 사용시는 'VSCode 설정 : "files.insertFinalNewline": true" 으로 해결 혹은 각 파일에 한줄씩 빈 줄을 추가하여 에러 해결하고 머지 해주시길 바랍니다.

57 changes: 57 additions & 0 deletions two-sum/hypoxisaurea.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'''
1. Brute Force 풀이:
배열의 각 위치 i를 기준으로 diff = target - nums[i] 를 계산하고
그 뒤쪽(i+1부터 끝까지) 요소들 중 nums[j] == diff 인 j를 찾으면
[i, j] 반환

시간 복잡도: O(n²)
이중 루프를 돌며 모든 쌍을 검사

공간 복잡도: O(1)
추가 자료구조를 사용하지 않고 상수 공간만 소모


2. Hash Map 풀이:
빈 딕셔너리 lookup = {} 준비
배열을 순회하며 각 요소 num에 대해 diff = target - num 을 계산

if diff in lookup:
보수가 이미 맵에 있으면 즉시 [lookup[diff], i] 반환
그렇지 않으면 lookup[num] = i 로 현재 값과 인덱스를 기록
순회 종료 후에도 못 찾으면 에러 발생

시간 복잡도: O(n)
한 번 순회하며 딕셔너리 조회·삽입이 평균 O(1)

공간 복잡도: O(n)
최악의 경우 모든 요소를 맵에 저장
'''


from typing import List

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
diff = target - nums[i]

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

raise ValueError('No answer')


class Solution2:
def twoSum(self, nums: List[int], target: int) -> List[int]:
lookup = {}

for i, num in enumerate(nums):
diff = target - num

if diff in lookup:
return [lookup[diff], i]

lookup[num] = i

raise ValueError('No answer')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파이썬으로 알고리즘 풀면서 raise 키워드 사용한 error 처리는 해본 적이 없네요. 좋은 코드 배워갑니다!

Loading