题目原文:
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.
题目大意:
找出一个数组的主元素,即在数组中出现的次数>n/2.
分析:
使用repeatTimes变量记录主元素重复次数,每次遇到重复的就+1,不重复的就-1.减到0时就更新当前主元素。(利用主元素出现次数比其他数出现之和多这一性质。)
源码:(language:c)
int majorityElement(int* nums, int numsSize) {
int i,mainElement,repeatTimes = 0;
//每次若不相同则减小这个计数,若相同则增加
for(i = 0;i<numsSize;i++) {
if(repeatTimes == 0){
mainElement = nums[i];
repeatTimes = 1;
}
else{
if(mainElement == nums[i])
repeatTimes++;
else
repeatTimes--;
}
}
return mainElement;
}
成绩:
8ms,beats 36.16%.众数:8ms 63.84%
Cmershen的碎碎念:
此题好像是考研408模拟题中的一道题,听说也经常在面试中出现。一开始我想到的是用HashMap记录每个元素出现的次数,最大的就是主元素。但这样的空间复杂度就是O(n),而上述算法有更优的O(1)空间复杂度。