题目描述:
Given an array of size n, find the majority element. The majority element is the element that appearsmore than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
我的代码:
主要是因为不了解vector。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int l=nums.size();
int a[l];
for(int i=0;i<l;i++){
a[i]=nums[i];
}
sort(a,a+l);
int t=0,s=a[0];
for(int i=0;i<l;i++){
if(a[i]==s)t++;
if(t>l/2)return s;
if(a[i]!=s){
s=a[i];
t=1;
}
}
}
};