arrays - 查找列表中的最小数字

标签 arrays go slice

我用 Go 编写了一个程序,它可以找到列表中的最小数字并且可以正常工作。 但是,我真的不明白其中的逻辑。你能解释一下它是如何工作的吗?

package main

import "fmt"

func main() {
    x := []int{
        48, 96, 86, 68,
        57, 82, 63, 70,
        37, 34, 83, 27,
        19, 97, 9, 17,
    }

    for i, num := range x {
        if num < i {
            fmt.Println(num)
        }
    }
}

Playground :https://play.golang.org/p/Awuw2Th1g2V

输出:

9

我教科书中的解决方案不同,我理解那里的逻辑。

最佳答案

要找到列表中的最小数字,您需要遍历列表并存储您当前找到的最小数字。将这个“迄今为止最小”的数字与列表中的其他数字进行比较,如果您发现一个较小的数字,请用它替换您的最小数字。在迭代结束时,您将知道列表中的最小数字。

smallest := x[0]            // set the smallest number to the first element of the list
for _, num := range x[1:] { // iterate over the rest of the list
    if num < smallest {     // if num is smaller than the current smallest number
        smallest = num      // set smallest to num
    }
}
fmt.Println(smallest)

关于arrays - 查找列表中的最小数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53182202/

相关文章:

java - 动态修改数组名称

go - 语法错误 : Non-declaration statement outside function body, 但所有内容都有声明

c# - 如何反转 int 的字节顺序?

c# - 不能在 ArrayList 和 Array 之间应用 ??-operator

golang gorilla/session 在检查 session 时得到 nil 值

go - 在 golang (gin) 中访问数组后参数

go - 在 go 中对一个 uint64 slice 进行排序

memory-leaks - 这会导致 Go 中的内存泄漏吗?

reflection - 为什么我不能使用反射来获取 slice 的地址?

python - 在 Python 中初始化一个固定大小的数组