dshun123456 2019-03-21 10:02
浏览 49
已采纳

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

I am working on printing the index of the numbers that leads to the sum that is entered through input by user. I have basically used the tradition method of using two loops of i & j and iterate until array length. However, when it comes to Go Language, we do have an option of getting index & key value of array using a different format in Go.

Here's my working code:

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
}

How do I do the same thing using :

for idx, key := range arr{
    for idx2, key2 := range arr {
        //statements
    }
}

Basically, I am not able to figure out initiating the inner index with +1 of outer index or may do it in a single loop.

  • 写回答

1条回答 默认 最新

  • dongzhu6900 2019-03-21 10:27
    关注

    Just iterate over a slice starting at idx+1:

    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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部