Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[suwi] Week 08 #975

Merged
merged 4 commits into from
Feb 2, 2025
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
44 changes: 44 additions & 0 deletions clone-graph/sungjinwi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""
풀이 :
재귀를 이용해서 dfs풀이
node를 복제하고 노드의 이웃된 노드에 대해서 재귀함수 호출을 통해 완성한다

clones 딕셔너리에 이미 복사된 node들을 저장해서 이미 복제된 node에 대해
함수를 호출하면 바로 return

노드의 수 : V(정점 : Vertex) 이웃의 수 : E(간선 : Edge)라고 할 때

TC : O(V + E)
노드와 이웃에 대해서 순회하므로

SC : O(V + E)
해시테이블의 크기가 노드의 수에 비례해서 커지고
dfs의 호출스택은 이웃의 수만큼 쌓이므로
"""

"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
from typing import Optional

class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
if not node :
return None

clones = {}

def dfs(node : Optional['Node']) -> Optional['Node']:
if node in clones :
return clones[node]
clone = Node(node.val)
clones[node] = clone
for nei in node.neighbors :
clone.neighbors.append(dfs(nei))
return clone

return dfs(node)
26 changes: 26 additions & 0 deletions longest-repeating-character-replacement/sungjinwi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
풀이 :
부분문자열 중에 가장 많은 빈도의 문자를 기준으로 다른 문자가 k개 이하로 있으면
같은 반복문자열로 만들 수 있다
sliding window 기법을 통해 최다빈도 문자와 다른 문자가 k개 초과이면 start를 이동시킨다

SC : O(N)
start, end포인터는 문자열 길이에 비례해 반복해서 이동하므로 (max 연산은 O(26))

TC : O(1)
counter 딕셔너리는 최대 알파벳 개수만큼의 메모리를 차지하므로 O(26)으로 상수이다다
"""

class Solution:
def characterReplacement(self, s: str, k: int) -> int:
start, end = 0, 0
counter = {}
max_len = 0
while end < len(s) :
counter[s[end]] = counter.get(s[end], 0) + 1
while end - start + 1 - max(counter.values()) > k :
counter[s[start]] -= 1
start += 1
max_len = max(max_len, end - start + 1)
end += 1
return max_len
17 changes: 17 additions & 0 deletions number-of-1-bits/sungjinwi.py
Copy link
Contributor

Choose a reason for hiding this comment

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

n의 범위가 int 로 정해져 있으니, 이를 이용해서 32자릿수를 모두 대조해보는 기똥찬 접는 방법이네요!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

이번주 문제들이 제 입장에선 꽤 어렵고 생소해서 칭찬해주신 풀이법 모두 달레님의 풀이를 그대로 쓴거라 민망하긴 하지만...ㅎㅎㅎ
감사한 코치님들 격려 덕분에 그래도 어떻게 매주 삐걱삐걱 해내고 있는거 같네요!
다음 주부터 하드 난이도 문제도 추가되서 좀 두렵지만 더 열심히 해보겠습니다

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""
풀이 : mask를 int 비트 수 만큼 이동시키면서 1의 개수 센다

TC : O(1)

SC : O(1)
"""

class Solution:
def hammingWeight(self, n: int) -> int:
mask = 1 << 31
cnt = 0
while mask :
if mask & n :
cnt += 1
mask >>= 1
return cnt
23 changes: 23 additions & 0 deletions sum-of-two-integers/sungjinwi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
풀이 :
비트 연산자 xor, and, shift를 이용해 수행한다
a는 a와 b의 xor연산 결과
-> a와 b의 set-bit가 겹치지 않는 위치에서의 합연산을 가능하게 함
b는 a와 b의 and연산 결과 << 1
-> a와 b가 둘 다 1인 위치에서 합을 통해 올림수로 올려주는 역할 수행

파이썬에서는 int가 32비트가 아니므로 1 32개로 이루어진 mask를 설정해주고
올림수 b가 32비트 범위를 벗어나지 않고 존재할동안 while문 연산을 진행한다
반복문 진행 후 32비트에 대해서만 return

TC : O(1)

SC : O(1)
"""

class Solution:
def getSum(self, a: int, b: int) -> int:
mask = 0xFFFFFFFF
while mask & b :
a, b = a ^ b, (a & b) << 1
return a & mask if b > 0 else a