Problem url:
https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem
Solution:
Results are generated in O(n)*log(n) since we are sorting the array first. We can transfer sorted array and compare each number with the next find to find the smallest difference.
func minimumAbsoluteDifference(arr []int32) int32 {
var f foo
f = arr
temp := Abs(f[0] - f[1])
sort.Sort(f)
fmt.Println(f)
for i:=0; i < len(f) - 1; i++ {
if Abs(f[i] - f[i+1]) < temp {
temp = Abs(f[i] - f[i+1])
}
}
return temp
}
// Abs returns the absolute value of x.
func Abs(x int32) int32 {
if x < 0 {
return -x
}
return x
}
//type foo that implements Sort for int32 type
type foo []int32
func (f foo) Len() int {
return len(f)
}
func (f foo) Less(i, j int) bool {
return f[i] < f[j]
}
func (f foo) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}