Skip to content

Instantly share code, notes, and snippets.

@yojkim
Created September 15, 2018 02:30
Show Gist options
  • Save yojkim/14406a1bf520642edc3488ba059d7ae3 to your computer and use it in GitHub Desktop.
Save yojkim/14406a1bf520642edc3488ba059d7ae3 to your computer and use it in GitHub Desktop.
func asteroidCollision(asteroids []int) []int {
if len(asteroids) <= 1 {
return asteroids
}
last := []int{asteroids[0]}
for _, ast := range asteroids[1:] {
for {
if len(last) == 0 {
last = append(last, ast)
break
}
top := last[len(last)-1]
if top * ast > 0 {
last = append(last, ast)
break
} else if top * ast < 0 {
if top < 0 && ast > 0 {
last = append(last, ast)
break
} else {
absTop := math.Abs(float64(top))
absAst := math.Abs(float64(ast))
if absTop < absAst {
last = last[:len(last)-1]
} else if absTop == absAst {
last = last[:len(last)-1]
break
} else {
break
}
}
}
}
}
return last
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment