Skip to content

[JustHm] Week 04 Solutions #1354

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

Merged
merged 5 commits into from
Apr 27, 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
29 changes: 29 additions & 0 deletions coin-change/JustHm.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// time: O(n*amount) space: O(amount)
class Solution {
func coinChange(_ coins: [Int], _ amount: Int) -> Int {
var queue: [(count: Int, total: Int)] = [(0, 0)] // (동전 개수, 누적 금액)
var visited = Set<Int>() // 중복 제거용
var index = 0 // 큐의 head

while index < queue.count {
let (count, total) = queue[index]
index += 1

if total == amount {
return count
}
if visited.contains(total) {
continue
}
visited.insert(total)
// BFS 방식
for coin in coins { // 모든 코인을 현재 누적금액에 한 번씩 더해서 큐에 저장
let newTotal = total + coin
if newTotal <= amount {
queue.append((count + 1, newTotal))
}
}
}
return -1
}
}
38 changes: 38 additions & 0 deletions find-minimum-in-rotated-sorted-array/JustHm.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// time: O(n), space: O(1)
// 투포인터로 양 끝에서 하나씩 줄여가며 가장 작은값 찾아 반환하기.
class Solution {
func findMin(_ nums: [Int]) -> Int {
guard nums.count != 1 else { return nums.first! }

var answer = Int.max
var left = 0
var right = nums.count

while right - left > 0 {
let temp = min(nums[left], nums[right - 1])
answer = min(answer, temp)
left += 1
right -= 1
}

return answer
}
}
// time: O(log n), space: O(1)
// 중간 값과 오른쪽 값중 가장 작은쪽을 기준으로 잘라가며 탐색함 (이진 탐색)
class Solution {
func findMin(_ nums: [Int]) -> Int {
guard nums.count != 1 else { return nums.first! }

var left = 0
var right = nums.count - 1

while left < right {
let mid = (left + right) / 2
if nums[mid] < nums[right] { right = mid }
else { left = mid + 1 }
}
return nums[right]
}
}

11 changes: 11 additions & 0 deletions maximum-depth-of-binary-tree/JustHm.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// time: O(n) space: O(n)
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
return dfs(root, 1)
}

func dfs(_ node: TreeNode?, _ n: Int) -> Int {
guard let node = node else { return n - 1 }
return max(dfs(node.left, n+1), dfs(node.right, n+1))
}
}
29 changes: 29 additions & 0 deletions merge-two-sorted-lists/JustHm.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// time: O(n+m) space: O(1)
class Solution {
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
// 전처리
guard list1 != nil, list2 != nil else { return list1 ?? list2 }
// 변수 정의
var answer: ListNode? = ListNode(0)
var top: ListNode? = answer
var list1 = list1
var list2 = list2
// 2개의 ListNode를 순회하면서 값을 보고 작은 순으로 저장 (ListNode에)
while list1 != nil && list2 != nil {
if let value1 = list1?.val, let value2 = list2?.val {
if value1 < value2 {
answer?.next = ListNode(value1)
list1 = list1?.next
}
else {
answer?.next = ListNode(value2)
list2 = list2?.next
}
answer = answer?.next
}
}
// 남은 노드들 연결하기
answer?.next = list1 ?? list2
return top?.next
}
}
42 changes: 42 additions & 0 deletions word-search/JustHm.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// time: O(N * M * 4^L) space: O(N * M + L)
// N 행 - M 열 - L word의 길이 (4방향을 탐색하기에 4^L)
class Solution {
func exist(_ board: [[Character]], _ word: String) -> Bool {
let words = Array(word)
var visited = Array(repeating: Array(repeating: false, count: board[0].count), count: board.count)
var startPoints = [(Int, Int)]()
// 먼저 시작 가능한 인덱스들 찾기 - O(n^2)
for i in board.indices {
for j in board[0].indices {
if board[i][j] == words[0] {
startPoints.append((i,j))
}
}
}
// 문자 찾아가기위한 DFS 내부함수 (backtracking)
func dfs(_ row: Int, _ col: Int, _ index: Int) -> Bool {
if row < 0 || col < 0 || row >= board.count || col >= board[0].count { return false }
if visited[row][col] { return false }
if board[row][col] != words[index] { return false }
if index + 1 == word.count { return true }

visited[row][col] = true

for dir in [(0, 1), (1, 0), (0, -1), (-1, 0)] {
let nextRow = row + dir.0
let nextCol = col + dir.1
if dfs(nextRow, nextCol, index + 1) {
return true
}
}

visited[row][col] = false
return false
}
// 문자 찾기
for pos in startPoints {
if dfs(pos.0, pos.1, 0) { return true }
}
return false
}
}