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.其他方法
利用快速排序的思想宇弛,每次確定一個(gè)數(shù)的位置落追,數(shù)組的中位數(shù)就是出現(xiàn)次數(shù)最多的數(shù)。