duanna2026 2018-03-05 02:45
浏览 4
已采纳

twoSum函数在不同的数组输入下的行为不同

When I run the following code, I get the expected answer [3, 4], which is the index of the 2 numbers that add up to my target variable. However, when I change the myArray input to []int{1,2,3,4,6,11,4,12} (I deleted the last 6), I get a panic. Please help me understand why this is happening.

func twoSum (nums []int, target int) []int {
    length := len(nums) - 1
    for i := range nums[:length] {
        for j := range nums[i + 1:] {
            if nums[i] + nums[j] == target {
                return []int{i, j}
                break
            }
        }
    }
    panic("should never happen")
}

func main() {
    myArray := []int{1,2,3,4,6,11,4,12}
    myTarget := 10
    fmt.Println(twoSum(myArray, myTarget))
}
  • 写回答

2条回答 默认 最新

  • dsgk0386 2018-03-05 03:00
    关注

    for j := range nums[i + 1:] {

    This does not work like you expect: j here is a 0-based index of a new slice, that you obtained after you resliced the nums with nums[i+1:].

    If you still want to have the absolute index in the nums slice you need to offset it manually, eg:

    jx := j + i + 1
    

    and then use jx instead of j

    Demo: https://play.golang.org/p/s7_tcHvu6fB

    Alternatively you may have used a good old indexed for instead of for-range as a nested loop:

    for j := i + 1; j < length; j++ {
    

    Demo: https://play.golang.org/p/-yF7cWYgYri

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错