arrays - 在列表中查找最小的数字
问题描述
我在 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)
}
}
}
游乐场: 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)
推荐阅读
- csv - 在 Jmeter 中,来自 CSV 文件的数据不是读取
- reactjs - 应用部署到生产服务器时返回 404
- c# - 如何在 ASP.NET MVC 的编辑视图中的下拉列表中填充值
- java - Java 反射:高负载时的 NoSuchMethodException
- jquery - 使用 Jquery SerializeArray() 获取 JSON 键值对
- php - 文件下载给出警报消息而不是下载它
- php - PHP 仅删除特定单词而不影响字符串的其余部分
- android - unity Builds 中的屏幕覆盖
- javascript - 如何使用反应路由器 dom v5.0.1 获取参数
- jenkins - 我应该如何在 git scm 中使用相同的参数?