Go 查找元素

数组查找元素

go中没有类似其他语言p中in_array() 方法

遍历

package main

import "fmt"

// Contains 数组是否包含某元素
func Contains(slice []string, s string) int {
	for index, value := range slice {
		if value == s {
			return index
		}
	}
	return -1
}

func main() {
	books := []string{"redis", "kafka", "go", "k8s"}
	search := "go"

	r := Contains(books,search)
	if r==-1 {
		fmt.Println("不存在")
	} else{
		fmt.Println("存在")
	}
}

map

切片先转为map,使用map判断元素是否存在

时间复杂度 O(1) 空间换取时间 大切片意味需要耗用大量的内存空间。

借助sort包

package main

import (
	"fmt"
	"sort"
)

func main() {
	books := []string{"redis", "kafka", "go", "k8s","n", "1", "a", "2", "你","sun"}
	search := "s"

	//对 slice 进行升序排序
	sort.Strings(books)

	//查找字符串 找到返回下标位置
	pos := sort.SearchStrings(books, search)
	if pos != len(books) {
		fmt.Printf("查找位置:%d\n", pos)  // 匹配下标还得比较下元素是否一致(设计)
		if search == books[pos] {
			fmt.Println("存在")
		} else {
			fmt.Println("不存在")
		}
	} else {
		fmt.Println("不存在")
	}
}

sort.SearchStrings 二分查找法 O(log n)

sort.SearchInts

sort.SearchFloat64s

大切片使用比range性能更佳。

posted @ 2020-05-04 02:35  walkingSun  阅读(6087)  评论(0编辑  收藏  举报
**/