问题描述:
数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5
示例 2:
输入:[3,2]
输出:-1
示例 3:
输入:[2,2,1,1,1,2,2]
输出:2
说明:
你有办法在时间复杂度为 O(N),空间复杂度为 O(1) 内完成吗?
方法一:
先对着数组进行排序(因为排好序后,数组中间的那个数即为主要元素)
在判断排好序的数组中间数是否是主要元素
class Solution {
public:int majorityElement(vector<int>& nums) {sort(nums.begin(), nums.end());int x = nums[nums.size() / 2];int count = 0;for(auto a:nums){if(a==x)count++;}if(count>nums.size()/2)//注意这里不是大于等于return x;elsereturn -1;}
};