作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我正在打印导致通过用户输入输入的总和的数字索引。我基本上使用了使用 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/
我是一名优秀的程序员,十分优秀!