you should change arrLen := len(nums) + 1
to arrLen := len(nums)
.
Your array length is 4. the indexes are 0,1,2,3 for this. but when you tried to do arrLen := len(nums) + 1
. the arrlen
value is now 5
. but you have only 4 element. and from your loop you are trying to get a element that is not present in array. that will give you a runtime error and it will panic.
this one will work for you:
package main
import "fmt"
func missingNumber(nums []int) int {
arrSum := 0
arrLen := len(nums)
for i := 0; i < arrLen; i++ {
arrSum += nums[i]
}
m := arrLen + 1
numSum := m * (m + 1) / 2
missingNumber := numSum - arrSum
return missingNumber
}
func main() {
nums := []int{1, 3, 4, 5}
result := missingNumber(nums)
fmt.Println(result)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…