ABUJA, Nigeria — Officials declared early Wednesday that Muhammadu Buhari had won a second term as president of Africa’s most populous country, where voters rejected a corruption-stained candidate in favor of a leader who promised to continue a campaign to eliminate graft.

Not long after midnight, election officials finished counting the votes, making it apparent that Mr. Buhari had defeated the leading candidate, Atiku Abubakar, by a wide margin in an election that was marred by pockets of violence. He was declared the winner shortly before 5 a.m.

On Wednesday morning, Mr. Abubakar released a statement calling the results a “sham election” and saying that he would contest the outcome in court. He cited what he called a “statistical impossibility” of the results in some states — where turnout was high despite the fact that life there has been upended by war — as well as anomalies in states that are opposition strongholds.