Can I win a gym battle or do I just need to survive?
I recently took over a gym that was being held by a single Flareon. I started the battle with a strong Vaporeon (lower level, but with type advantage). I got the Flareon down to a sliver of HP left while my Vaporeon was around 75%. At that point, attacks seemed to just stop dealing damage. The Flareon took out my Vaporeon, and then my next Vaporeon, and my next Pokémon! With my fourth, I only attacked once, and then just dodged every attack until time ran out. Once time ran out, the Flareon fell over on its own (I hadn't attacked recently) and I won.
Can I knock out the last gym Pokémon, or do I have to just survive until the time runs out? Is there some special move or item that can prevent a Pokémon from being knocked out?
It's a bug in the game due to server or connection problems.
Note however that you will usually be refunded health and special move charge back to when you should have killed the opposing Pokemon. In your case if you check your Pokemon it's likely (although not guaranteed) that the two other Pokemon will still actually be at full health.