原题
题很简单,直接排序后输出中间的值即可,而且还不需要判断
return sorted(nums)[int(len(nums)>>1)]
但大多数sort或者sorted 都是以快排实现
复杂度是n*log(n)
现在考虑一种时间复杂度为n的方法
class Solution {
public:
int majorityElement(vector<int>& nums) {
//出现次数大于一半,则多数元素的个数比其他元素个数加起来还要多
//相同加一,不同减一,遍历到最后时只有多数元素才可以保证结果为正数
int count=1;
int temp = nums[0];
for(int i=1;i<nums.size();i++)
{
if(temp == nums[i])
count++;
else
{
count--;
if(count==0)
temp = nums[i+1];
}
}
return temp;
}
};