Documenting LeetCode solving.
Start to practice Go fluency.
Q62
Medium. Graphs
func numIslands(grid [][]byte) int {
res := 0
m, n := len(grid), len(grid[0])
var dfs func(i, j int)
dfs = func(i, j int) {
if i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0' {
return
}
grid[i][j] = '0'
dfs(i + 1, j)
dfs(i - 1, j)
dfs(i, j + 1)
dfs(i, j - 1)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == '1' {
res += 1
dfs(i, j)
}
}
}
return res
}
Q63
232. Implement Queue using Stacks
Easy.
No need to use two stacks in Go.
type MyQueue []int
func Constructor() MyQueue {
return MyQueue{}
}
func (this *MyQueue) Push(x int) {
*this = append(*this, x)
}
func (this *MyQueue) Pop() int {
res := (*this)[0]
*this = (*this)[1:]
return res
}
func (this *MyQueue) Peek() int {
return (*this)[0]
}
func (this *MyQueue) Empty() bool {
return len(*this) == 0
}
Q64
225. Implement Stack using Queues
Easy.
type MyStack struct {
// Different struct to initialize
data []int
}
func Constructor() MyStack {
return MyStack{make([]int, 0)}
}
func (this *MyStack) Push(x int) {
this.data = append(this.data, x)
}
func (this *MyStack) Pop() int {
// Different here
res := this.data[len(this.data) - 1]
this.data = this.data[:len(this.data) - 1]
return res
}
func (this *MyStack) Top() int {
return this.data[len(this.data) - 1]
}
func (this *MyStack) Empty() bool {
return len(this.data) == 0
}
Q65
341. Flatten Nested List Iterator
Medium
type NestedIterator struct {
// Holds pointers
queue []*NestedInteger
}
func Constructor(nestedList []*NestedInteger) *NestedIterator {
iter := &NestedIterator{queue: make([]*NestedInteger, 0)}
iter.dfs(nestedList)
return iter
}
func (this *NestedIterator) Next() int {
res := this.queue[0]
this.queue = this.queue[1:]
return res.GetInteger()
}
func (this *NestedIterator) HasNext() bool {
return len(this.queue) > 0
}
func (this *NestedIterator) dfs(nestedList []*NestedInteger) {
for i := 0; i < len(nestedList); i++ {
if nestedList[i].IsInteger() {
this.queue = append(this.queue, nestedList[i])
} else {
this.dfs(nestedList[i].GetList())
}
}
}
ย