Roy Cooper, a Democrat and former North Carolina governor, had enjoyed a strong lead over his opponent, Michael Whatley, for much of the campaign.