php Editor Shinichi may encounter the problem of not finding errors when writing Go scripts, causing the scripts to fail to work as expected. This is a common problem, but one that can be solved. This article will introduce you to some possible causes of this problem and provide some solutions to help you solve this problem more easily and make the Go script run smoothly.
I am trying to solve this leetcode problem https://leetcode.com/problems/two-sum/ But for some reason it doesn't work and I really don't understand what's going wrong. It just returns [-1 -1] while [100 137] is the correct 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 nums[starter], nums[i], all loops were working as expected, I used fmt.println() to log their values and it seemed to be working correctly Location, don't know what's wrong
The problem with your code is that it never gets inside the if
if target-nums[starter] == nums[i]
starter The variable will remain at 0 after the first loop because it will only store the first value less than the target.
If you are not worried about performance, this o(n²) function can produce the correct results:
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 above is the detailed content of Not found error, Go script not working as expected. For more information, please follow other related articles on the PHP Chinese website!