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))
}