代码实现:
思路:摩尔投票算法
int majorityElement(int *nums, int numsSize) {int candidate = -1;int count = 0;for (int i = 0; i < numsSize; i++) {if (count == 0) {candidate = nums[i];}if (nums[i] == candidate) {count++;} else {count--;}}count = 0;int length = numsSize;for (int i = 0; i < numsSize; i++) {if (nums[i] == candidate) {count++;}}return count * 2 > length ? candidate : -1; }