..
几个golang的面试编程题目
前几天出去面试了,有几个编程现场编程题目,我这里记录一下:
字符串翻转
- 方法1
// 非常低的效率
func reverse(s string)string{
var buffer = []rune(s)
var arr []rune
for index := range buffer{
arr = append([]rune{buffer[index]},arr ...)
}
return string(arr)
}
- 方法2
func reverse(s string)string{
var n string
for _,v := range s{
n = string(v)+n
}
return n
}
10个goroutine分别打印 1, 2, 3 … 10
- 方法1
package main
import "sync"
var wg sync.WaitGroup
func fx(n int){
defer wg.Done()
println(n)
}
func main(){
for i := 1 ;i <=10;i++{
wg.Add(1)
go fx(i)
}
wg.Wait()
}
- 方法2
package main
import "sync"
// 生产者消费原理
var wg sync.WaitGroup
func fx(c chan int){
defer wg.Done()
value , ok := <- c
if !ok {
return
}
println(value)
if value == 10{
close(c)
return
}
c<-value+1
}
func main(){
var c = make(chan int)
for i := 0 ;i < 10 ;i++{
wg.Add(1)
go fx(c)
}
c<-1
wg.Wait()
}
前序遍历二叉树
type Node struct{
Value int
Left *Node
Right *Node
}
func loop(tree *Node){
if tree == nil{
return
}
println(tree.Value)
loop(tree.Left)
loop(tree.Right)
}
求树的最大深度
type Node struct{
Value int
Childs []*Node
}
func deep(tree *Node) int{
if tree == nil{
return 0
}
var childMaxDeep int = 0
for index := range tree.Childs{
var dp = deep(tree.Childs[index])
if dp > childMaxDeep{
childMaxDeep = dp
}
}
return childMaxDeep + 1
}