1.描述
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
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
2.分析
因为主元素在数组中的出现次数严格大于数组元素个数的二分之一,因此排序后数组的前半部分或后半部分一定全为主元素,取中间数即为主元素。
3.代码
class Solution {
public:
/*
* @param nums: a list of integers
* @return: find a majority number
*/
int majorityNumber(vector<int> &nums) {
// write your code here
sort(nums.begin(),nums.end());
int n=nums.size();
return nums[n/2];
}
};
4.总结
贪心算法的好处在于一眼看到问题的本质,既然主元素在数组中严格出现一半以上,排序后中间数即为所求主元素。