1.描述
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:Special thanks to @ts for adding this problem and creating all test cases.
2.分析
3.代码
int majorityElement(int* nums, int numsSize) {
if (NULL == nums || numsSize <= 0 ) exit(-1);
int majority = nums[0];
unsigned int count = 1;
for (unsigned int i = 1; i < numsSize; ++i) {
if (count == 0) {
majority = nums[i];
++count;
} else {
count += majority == nums[i] ? 1 : -1;
}
}
return majority;
}
4.其他方法
利用快速排序的思想,每次确定一个数的位置,数组的中位数就是出现次数最多的数。