【题目描述】
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.
【思路】将vector中的数按大小排序,一旦有数连续出现超过n/2次,即为绝大多数。
【代码】
class Solution {
public:
int majorityElement(vector<int>& nums) {
int n=nums.size();
int cnt,tmp;
sort(nums.begin(),nums.end());
cnt=1;
tmp=nums[0];
for(int i=1;i<n;i++){
if(nums[i]==tmp) cnt++;
else{
tmp=nums[i];
cnt=1;
}
if(cnt>n/2) return nums[i];
}
return tmp;
}
};