The challenge
You will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer.
Examples:
[1, -1, 2, -2, 3] => 3
3
has no matching negative appearance
[-3, 1, 2, 3, -1, -4, -2] => -4
-4
has no matching positive appearance
[1, -1, 2, -2, 3, 3] => 3
(the only-positive or only-negative integer may appear more than once)
The solution in Golang
Option 1:
package solution
func Solve(arr []int) int {
hash := make(map[int]bool)
ans := 0
for _, entry := range arr {
if _, value := hash[entry]; !value {
hash[entry] = true
ans += entry
}
}
return ans
}
Option 2:
package solution
func Solve(a []int) int {
s, n := 0, 0
for _, v := range a {
s += v
if v < 0 { n-- } else { n++ }
}
if n < 0 { n = -n }
return s/n
}
Option 3:
package solution
func Find(arr []int, elem int) bool {
for _, x := range arr {
if elem == x {
return true
}
}
return false
}
func Solve(arr []int) int {
for _, x := range arr {
if !Find(arr, -x) {
return x
}
}
return 0
}
Test cases to validate our solution
package solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func dotest(arr []int, exp int) {
var ans = Solve(arr)
Expect(ans).To(Equal(exp))
}
var _ = Describe("Example tests", func() {
It("It should work for basic tests", func() {
dotest([] int{1,-1,2,-2,3}, 3)
dotest([] int{-3,1,2,3,-1,-4,-2}, -4)
dotest([] int{1,-1,2,-2,3,3}, 3)
dotest([] int{-110,110,-38,-38,-62,62,-38,-38,-38}, -38)
dotest([] int{-9,-105,-9,-9,-9,-9,105}, -9)
})
})