169. Majority Element
Easy
1438129FavoriteShare
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.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
这道题挺简单的,一次AC了。暴力法,一开始排了序,然后用了两个指针去取相同的数的个数。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int t=nums.size()/2;
sort(nums.begin(),nums.end());
int count=0;
int i=0;
int j=0;
while(i<nums.size())
{
j=i;
while(nums[i]==nums[j])
{
count++;
j++;
if(count>t)return nums[i];
}
i++;
}
return 0;
}
};