汉风 發表於 2020-5-4 02:35:00

Go 查找元素

<p></p><div class="toc"><div class="toc-container-header">目录</div><ul><li>数组查找元素<ul><li>遍历</li><li>map</li><li>借助sort包</li></ul></li></ul></div><p></p>
<h1 id="数组查找元素">数组查找元素</h1>
<p>go中没有类似其他语言p中in_array() 方法</p>
<h2 id="遍历">遍历</h2>
<pre><code class="language-go">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("存在")
        }
}
</code></pre>
<h2 id="map">map</h2>
<p>切片先转为map,使用map判断元素是否存在</p>
<p>时间复杂度 O(1)空间换取时间    大切片意味需要耗用大量的内存空间。</p>
<h2 id="借助sort包">借助sort包</h2>
<pre><code class="language-go">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 {
                        fmt.Println("存在")
                } else {
                        fmt.Println("不存在")
                }
        } else {
                fmt.Println("不存在")
        }
}
</code></pre>
<p>sort.SearchStrings 二分查找法O(log n)</p>
<p>sort.SearchInts</p>
<p>sort.SearchFloat64s</p>
<p>大切片使用比range性能更佳。</p><br><br>
来源:https://www.cnblogs.com/followyou/p/12825072.html
頁: [1]
查看完整版本: Go 查找元素