gpt4 book ai didi

arrays - 如何在 Go 中使用数组范围添加嵌套循环的索引?

转载 作者:数据小太阳 更新时间:2023-10-29 03:44:13 25 4
gpt4 key购买 nike

我正在打印导致通过用户输入输入的总和的数字索引。我基本上使用了使用 i 和 j 的两个循环并迭代直到数组长度的传统方法。然而,当涉及到 Go 语言时,我们确实可以选择使用 Go 中的不同格式获取数组的索引和键值。

这是我的工作代码:

func findKIndex(arr []int, k int) (int, int) {
index1, index2 := 0, 0
Length := len(arr)
for i := 0; i < Length; i++ {
for j := i + 1; j < Length; j++ {
if arr[i]+arr[j] == k {
index1 = i
index2 = j
}
}
}
return index1, index2
}

我如何使用 :

做同样的事情
for idx, key := range arr{
for idx2, key2 := range arr {
//statements
}
}

基本上,我无法弄清楚用外部索引的 +1 启动内部索引,或者可能在一个循环中完成。

最佳答案

只需遍历从 idx+1 开始的 slice :

https://play.golang.org/p/KDITT8zQ6q-

for idx, key := range arr{
for idx2, key2 := range arr[idx+1:] {
//actual second index is idx + idx2 + 1
//statements
}
}

关于arrays - 如何在 Go 中使用数组范围添加嵌套循环的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55286621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com