主元素
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
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
一开始想用枚举法写,后来看题目,主元素个数是严格大于所有元素个数的1/2,所以就想到了排序,然后输出中间值。
代码:
int majorityNumber(vector<int> &nums) {
// write your code here
int n=nums.size();
sort(nums.begin(),nums.end());
return nums[n/2];
浙公网安备 33010602011771号