描述:
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的【二分之一】。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.
样例
给出数组[1,1,1,1,2,2,2],返回 1
比较好的有两种,一种是用哈希表,这种方法需要O(n)的时间和空间,另一种是用一种叫摩尔投票法 Moore Voting,需要O(n)的时间和O(1)的空间,比前一种方法更好。这种投票法先将第一个数字假设为众数,然后把计数器设为1,比较下一个数和此数是否相等,若相等则计数器加一,反之减一。然后看此时计数器的值,若为零,则将当前值设为候选众数。以此类推直到遍历完整个数组,当前候选众数即为该数组的众数。
代码如下:
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number
*/
int majorityNumber(vector<int> nums) {
// write your code here
int res = 0, int cnt = 0;
for(int num : nums){
if (cnt == 0) {res = num; ++cnt;}
else (num == res)? ++cnt, --cnt;
}
return res;
}
};
注:(int num:nums)
就是把nums这个数组进行遍历,它有多少个数,就遍历多少遍。
遍历的时候每次就把其中的一个值给num;
不确定数组中是否存在主元素时的解法:http://blog.csdn.net/tyf1271858074/article/details/45150093