today, i decide to write blog in english. let's start
i think this problem is so easy by using sort or extra space. if you use sorting, you can get the middle number after sorting with O(nlogn). if you use extra space, you can design a data structure like map e.t.c. you can through the array one time and record the appearance of each number. these solutions are so basic. so i did't type them. when i look at other's solution, there are genius solution which is very smart and beautiful. let me show it:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int major=nums[0];
int count=1;
for(int i=1;i<nums.size();i++){
if(count==0){
major=nums[i];
count++;
}
else if(major==nums[i])
count++;
else
count--;
}
return major;
}
};
the idea : for the major, because its account is larger than half, so only this number can not decrease to zero. for other number, they will decrease to zero, then be replaced by next number.
mark mark