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

[jungsiroo] Week 7 #925

Merged
merged 6 commits into from
Jan 25, 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
31 changes: 31 additions & 0 deletions longest-substring-without-repeating-characters/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""
딕셔너리를 사용하여 이전에 나왔던 인덱스를 기억
중복되지 않았다면 answer를 저장해 나감
중복이 발생하고 begin과 end사이라면 중복 발생 원인 다음을 begin으로 세팅 후 다시 계산

Time Complexity : O(n)
Space Complexity : O(n)
Copy link
Contributor

Choose a reason for hiding this comment

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

이번에 리뷰하면서 문제를 다시 읽어봤는데, s의 길이와 더불어 카디널리티 조건도 있는것 같아요.
symbols가 과연 어디까지 나타내는걸까 싶기는 한데, 결과적으로 상수값이 되어 O(1)라고도 할 수 있지 않을까 싶네요

  • 문제의 조건: s consists of English letters, digits, symbols and spaces.


"""
answer, begin, end = 0, 0, 0
hash_map = dict()

while end < len(s):
ch = s[end]
hash_map[ch] = hash_map.get(ch, -1)

if hash_map[ch] == -1: #한 번도 나오지 않았다.
hash_map[ch] = end
answer = max(answer, end-begin+1)
else:
if begin<=hash_map[ch]<end: #중복이 생겼다.
Copy link
Contributor

Choose a reason for hiding this comment

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

< end 조건은 불필요해 보이는데 혹시 필요한 상황이 있을까요?

begin = hash_map[ch]+1
else:
answer = max(answer, end-begin+1)
hash_map[ch] = end
end += 1

return answer

50 changes: 50 additions & 0 deletions number-of-islands/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
# TC : O(n*m)
# SC : O(n*m)

m, n = len(grid), len(grid[0])
dx = [-1,1,0,0]
dy = [0,0,-1,1]

def in_range(r, c):
if r<0 or c<0 or r>=m or c>=n:
return False
return True

# DFS Way

def dfs(r, c):
grid[r][c] = 'x'

for i in range(4):
nr, nc = r+dx[i], c+dy[i]
if not in_range(nr, nc) or grid[nr][nc] != '1':
continue
dfs(nr, nc)

# BFS Way
from collections import deque
def bfs(r, c):
grid[r][c] = 'x'
queue = deque()
queue.append([r, c])

while queue:
cr, cc = queue.popleft()
for i in range(4):
nr, nc = cr+dx[i], cc+dy[i]

if not in_range(nr, nc) or grid[nr][nc] != '1':
continue
grid[nr][nc] = 'x'
queue.append([nr, nc])

ret = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
bfs(i, j)
ret += 1
return ret

29 changes: 29 additions & 0 deletions reverse-linked-list/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# iterative way

"""
prev, curr = None, head
while curr:
tmp_nxt = curr.next

curr.next = prev
prev, curr = curr, tmp_nxt

return prev
"""

# Recursive Way
if head is None or head.next is None:
return head

new_head = self.reverseList(head.next)
head.next.next = head # reversing pointer
head.next = None
return new_head

# 둘 다 시간복잡도 O(n)
# 하지만 재귀의 경우 콜스택에 따른 공간복잡도 O(n)을 소요
# iterative 방식은 O(1)


43 changes: 43 additions & 0 deletions set-matrix-zeroes/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""

"""
# Naive change : save rows and cols
# SC : O(m+n)
row_zero, col_zero = set(), set()

rows, cols = len(matrix), len(matrix[0])
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
row_zero.add(i)
col_zero.add(j)

for i in range(rows):
for j in range(cols):
if i in row_zero or j in col_zero:
matrix[i][j] = 0
"""

# Constant Space Complexity using bitmasking
Copy link
Contributor

Choose a reason for hiding this comment

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

와우,, 파이썬은 200비트 정수를 사용할수 있네요

# 0인 구간을 toggle 시켜놓고 확인하는 방법
def is_on(number, k):
return (number & (1<<k)) != 0

row_zero, col_zero = 0, 0

rows, cols = len(matrix), len(matrix[0])
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
row_zero |= (1 << i)
col_zero |= (1 << j)

for i in range(rows):
for j in range(cols):
if is_on(row_zero, i) or is_on(col_zero, j):
matrix[i][j] = 0

15 changes: 15 additions & 0 deletions unique-paths/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from math import comb

class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# mathematic way
# 중학교 때 배운 최단거리 조합으로 구하기 문제
# 문제 자체가 오른쪽, 아래밖에 못가기에 최단거리가 될 수 밖에 없음

"""
TC : O(max(m, n))
SC : O(1)
"""

return comb(m+n-2, m-1)
Copy link
Contributor

Choose a reason for hiding this comment

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

역시 파이썬의 편의성 최고네요 👍


Loading