找不到错误,Go脚本不按预期工作。

huangapple go评论79阅读模式
英文:

Can’t find the error, Go script doesn't work as expected

问题

我尝试解决这个Leetcode问题https://leetcode.com/problems/two-sum/,但由于某种原因它不起作用,我真的不明白问题出在哪里。它只返回[-1 -1],而正确的输出应该是[100 137]。

我没有任何调试技巧,所以我只确保nums[starter]、nums[i]以及所有的循环都按预期工作,我使用了fmt.Println()来记录它们的值,看起来它们都在正确的位置,我不知道问题出在哪里。

英文:

I tried to solve this Leetcode problem https://leetcode.com/problems/two-sum/
But it doesn't work for some reason, I really can't undestand what's wrong.
it just returns [-1 -1] whereas [100 137] is the right output.

package main

import "fmt"

func main() {
	arr := []int{10, 40, 1, 4, 100, 137}
	targetVal := 237
	// twoSum(arr, targetVal)
	fmt.Println(twoSum(arr, targetVal))
}

func twoSum(nums []int, target int) []int {
	starter := 0
	// loop which is supposed to find first occurence of element that is less than target
	for i := 0; i < len(nums); i++ {
		if nums[i] < target {
			starter = i
			break
		}
	}
	// loop that iterates over remaining part of a slice (starting from nums[starter])
	for i := starter; i < len(nums); i++ {
		if target-nums[starter] == nums[i] {
			return []int{nums[starter], nums[i]}
		}
	}
	return []int{-1, -1}
}

I don’t have any debugging skills at the moment, so I just made sure that nums[starter], nums[i], all loops work as intended, I used fmt.Println() to log their values, and it seems to be in the right place, Idk what is wrong

答案1

得分: 0

你的代码问题在于它从未进入 if 语句块中的代码:

if target-nums[starter] == nums[i]

在第一个循环通过后,starter 变量将保持为 0,因为它只会存储小于目标值的第一个值。

如果你不担心性能问题,下面这个 O(n²) 的函数可以得到正确的结果:

func twoSum(nums []int, target int) []int {
    for i := 0; i < len(nums); i++ {
        for j := 0; j < len(nums); j++ {
            if nums[i]+nums[j] == target && i != j {
                return []int{j, i}
            }
        }
    }
    return []int{-1, -1}
}
英文:

The problem with your code is that it never goes inside the if

if target-nums[starter] == nums[i]

The starter variable will remain at 0 after passing through the first loop, as it will store only the first value smaller than the target.

If you're not worried about performance this O(n²) function can produce the right result:

func twoSum(nums []int, target int) []int {
    for i := 0; i &lt; len(nums); i++ {
	    for j := 0; j &lt; len(nums); j++ {
		    if nums[i]+nums[j] == target &amp;&amp; i != j {
			    return []int{j, i}
		    }
	    }
    }
    return []int{-1, -1}
}

huangapple
  • 本文由 发表于 2023年3月9日 19:26:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定