dshun123456 2019-03-21 18: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 18: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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题