Sandoval hits game-ending HR, Giants beat Royals