Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
53 changes: 53 additions & 0 deletions number-of-connected-components-in-an-undirected-graph/flynn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
풀이
- DFS와 hashmap(set)을 이용하여 풀이할 수 있습니다
- 이전에 풀이했던 course schedule 문제와 유사합니다
Big O
- N: 노드 개수
- E: 간선의 개수
- Time complexity: O(N)
- 전체 노드를 최대 1번씩 조회합니다
- Space complexity: O(N + E)
- adjacency list의 크기는 E에 비례하여 증가합니다
- 두 set의 크기는 N에 비례하여 증가합니다
- check 함수의 재귀 호출 스택 깊이 또한 최악의 경우, N에 비례하여 증가합니다
*/

func countComponents(n int, edges [][]int) int {
adj := make(map[int][]int)
for _, edge := range edges {
adj[edge[0]] = append(adj[edge[0]], edge[1])
adj[edge[1]] = append(adj[edge[1]], edge[0])
}
// Go는 {int: bool} hashmap을 set처럼 사용함
checking := make(map[int]bool) // 현재 진행중인 DFS 탐색에서 방문한 노드를 기록함
checked := make(map[int]bool) // 모든 탐색이 끝난 노드를 기록함
// 각 node를 조회하는 함수
var check func(int)
check = func(i int) {
// 이미 방문한 적이 있는 node라면 탐색할 필요가 없음
if _, ok := checked[i]; ok {
return
}
checking[i] = true
for _, nxt := range adj[i] {
if _, ok := checking[nxt]; ok {
continue
}
check(nxt)
}
delete(checking, i)
checked[i] = true
}

res := 0
for i := 0; i < n; i++ {
if _, ok := checked[i]; ok {
continue
}
res++
check(i)
}

return res
}
34 changes: 34 additions & 0 deletions remove-nth-node-from-end-of-list/flynn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
풀이
- n+1 간격을 유지하며 이동하는 두 개의 포인터를 이용하면 one-pass로 해결할 수 있습니다
Big O
- M: 링크드리스트의 길이
- Time complexity: O(M)
- Space complexity: O(1)
*/

/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/

func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummy := &ListNode{Next: head}

slow := dummy
fast := dummy
for i := 0; i < n+1; i++ {
fast = fast.Next
}

for fast != nil {
slow = slow.Next
fast = fast.Next
}
slow.Next = slow.Next.Next

return dummy.Next
}
38 changes: 38 additions & 0 deletions same-tree/flynn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
풀이
- 재귀함수를 이용해서 풀이할 수 있습니다
Big O
- N: 트리 노드의 개수
- H: 트리의 높이 (logN <= H <= N)
- Time complexity: O(N)
- 모든 노드를 최대 1번 탐색합니다
- Space complexity: O(H)
- 재귀 호출 스택의 깊이는 H에 비례하여 증가합니다
*/

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSameTree(p *TreeNode, q *TreeNode) bool {
// base case
if p == nil && q == nil {
return true
} else if p == nil || q == nil {
return false
}

if p.Val != q.Val {
return false
}

if !isSameTree(p.Left, q.Left) || !isSameTree(p.Right, q.Right) {
return false
}

return true
}