涉及知识点
- 递归
- golang中struct的定义
- 切片的初始化(指定类型和长度)
- 二叉树的实现
- 验证slice是否是有序列的
验证slice是否是有序列的
- 手写
//验证函数
func isSort(values []int) bool {
for i:=1;i<len(values);i++{
if values[i-1]>values[i]{
return false
}
}
return true
}
- 利用sort库
sort.SliceIsSorted(s, func(i, j int) bool {
if i<j {
return true
}else {
return false
}
})
- 一步搞定
sort.IntsAreSorted(s)
type tree struct{
value int
left,right *tree
}
func Sort(values []int){
var root* tree
for _,v :=range values {
root = add(root, v)
}
appendValues(values[:0],root)
}
func appendValues(values []int,t *tree) []int {
if t!= nil {
values = appendValues(values, t.left)
values = append(values, t.value)
values = appendValues(values, t.right)
}
return values
}
func add(t *tree, value int) *tree {
if t == nil {
t = new(tree)
t.value = value
return t
}
if t.value < value {
t.left = add(t.left,value)
} else {
t.right = add(t.right,value)
}
return t
}
验证函数isSort
中为什么不判定是否为nil
,在buildin.go中对len函数的说明可知:Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
// The len built-in function returns the length of v, according to its type:
// Array: the number of elements in v.
// Pointer to array: the number of elements in *v (even if v is nil).
// Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
// String: the number of bytes in v.
// Channel: the number of elements queued (unread) in the channel buffer;
// if v is nil, len(v) is zero.
// For some arguments, such as a string literal or a simple array expression, the
// result can be a constant. See the Go language specification's "Length and
// capacity" section for details.
func len(v Type) int