1.链表翻转
func (n *node) reverse() *node {
var res *node
cur := n
var pre *node
for {
next := cur.next
cur.next = pre
pre = cur
cur = next
if cur == nil {
return pre
}
}
return res
}
2.爬楼梯
func climbStairs(n int) int {
n1,n2,num :=0,0,1
for i:=1;i<=n;i++{
n1 = n2
n2 = num
num = n1+n2
}
return num
}
3.冒泡法
func bubbleSort(arr []int) {
for i := 0; i < len(arr)-1; i++ {
for j := 0; j < len(arr)-i-1; j++ {
if arr[j] > arr[j+1] {
arr[j], arr[j+1] = arr[j+1], arr[j]
}
}
}
}
4.快速排序法
func quickSort(arr []int) []int {
if len(arr) <= 1 {return arr}
middleValue := arr[0]
left, right := []int{}, []int{}
for _, num := range arr[1:] {
if num <= middleValue {
left = append(left, num)
} else {
right = append(right, num)
}
}
leftSorted := quickSort(left)
rightSorted := quickSort(right)
result := make([]int, len(leftSorted)+len(rightSorted)+1)
copy(result, leftSorted)// 复制左子数组到结果切片
result[len(leftSorted)] = middleValue
copy(result[len(leftSorted)+1:], rightSorted) // 复制右子数组到结果切片
return result
}
5.二分查找法
func BinarySearch(arr []int, target int) int {
left, right := 0, len(arr)-1
for left <= right {
mid := left + (right-left)/2
if arr[mid] == target {
return mid
} else if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return -1