首页 > 解决方案 > 在列表中查找最小的数字

问题描述

我在 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

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

标签: arraysgoslice

解决方案


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

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)

推荐阅读