题号:169
难度:Easy
链接:https://leetcode.cn/problems/majority-element/comments/
思路
根据定义,多数元素出现次数总是大于 $n/2$ 向下取整。不难想到,若数组有序,其必然在下标 $n/2$ 处出现,故只需一次排序即可。‘、
代码
#include <vector>
#include <algorithm>
using std::vector;
using std::sort;
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()>>1];
}
};
Comments NOTHING