4 回答

TA貢獻1788條經驗 獲得超4個贊
要找到列表中的最小數字,您需要遍歷列表并存儲您當前找到的最小數字。將這個“迄今為止最小”的數字與列表中的其他數字進行比較,如果您發現一個較小的數字,請用它替換您的最小數字。在迭代結束時,您將知道列表中的最小數字。
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)

TA貢獻2037條經驗 獲得超6個贊
您提供的示例程序純屬巧合。如果正確的值 9 是切片中的第一個,則根本不會有輸出。
有多種方法可以達到識別最小int的目的(還有更多的方法):
func smallestOfCopyWithSort(in []int) int {
// Make a copy, so we do not have to modify the original slice.
// Note: Do NOT use this approach, it is here only for completeness.
copy := append([]int(nil), in...)
sort.Ints(copy)
return (copy[0])
}
func smallestWithSort(in []int) int {
// Sort the slice.
// Note that it will be modified and you
// need to make sure that it will always
// be sorted, even when you add new values.
sort.Ints(in)
return (in[0])
}
func smallestWithMattsApproach(in []int) int {
smallest := in[0] // set the smallest number to the first element of the list
for _, num := range in[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
}
}
return smallest
}
@Matt 的方法可能是最好的方法,因為它非常快,無需修改原始切片。這實際上取決于您想要實現的目標。這里有一些基準
$ go test -test.benchmem -bench=. -test.cpu 1,2,4 -test.benchtime=10s
goos: darwin
goarch: amd64
pkg: <redacted>
BenchmarkSortWithCopy 5000000 345 ns/op 160 B/op 2 allocs/op
BenchmarkSortWithCopy-2 5000000 354 ns/op 160 B/op 2 allocs/op
BenchmarkSortWithCopy-4 5000000 352 ns/op 160 B/op 2 allocs/op
BenchmarkMattsApproach 100000000 15.1 ns/op 0 B/op 0 allocs/op
BenchmarkMattsApproach-2 100000000 15.1 ns/op 0 B/op 0 allocs/op
BenchmarkMattsApproach-4 100000000 15.2 ns/op 0 B/op 0 allocs/op
BenchmarkSort 2000000000 0.00 ns/op 0 B/op 0 allocs/op
BenchmarkSort-2 2000000000 0.00 ns/op 0 B/op 0 allocs/op
BenchmarkSort-4 2000000000 0.00 ns/op 0 B/op 0 allocs/op
毫不奇怪,smallestOfCopyWithSort如果多次調用,它比其他方法慢幾個數量級。
Matts 的方法非常快,不會復制或修改任何內容。
但是,如果您需要多次訪問最小數量的切片,則對切片進行排序(升序)并簡單地訪問第一個成員會更高效。這樣做的原因是切片將被修改為排序順序。但是,這種方法有一個警告:您要么在向切片添加值時非常小心,要么在每次修改它時都使用它,這可能會抵消性能優勢,具體取決于您的讀取和寫入比率/從切片。就個人而言,我發現smallestWithSort我最常使用的解決方案,因為我正在使用的切片通常不會改變。
結論
如果您只需要訪問最小的數字一次或者切片值的順序很重要,請使用 Matt 的方法。如果順序無關緊要并且您需要多次訪問最小的數字,您可能應該使用smallestWithSort,同時牢記約束條件。

TA貢獻1818條經驗 獲得超7個贊
在
for i, num := range x {
if num < i {
fmt.Println(num)
}
}
這里,i代表索引,num代表價值。因此,您的if條件表示值小于索引然后打印該值。因為,9 值是 9,索引是 14。所以它打印 9,這不是你想要的。

TA貢獻1790條經驗 獲得超9個贊
返回python中列表的最小數量
def find_smallest_number(input_list):
d=[]
for num in input_list:
for i in numbers:
if num<i:
if d==[]:
d.append(num)
else:
for j in d:
if j>num:
d.remove(j)
d.append(num)
return d
- 4 回答
- 0 關注
- 188 瀏覽
添加回答
舉報