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.
class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(),nums.end());
return nums[n/2];
}
};
本文介绍了一种寻找多数元素的方法,即数组中出现次数超过一半的元素。假设数组非空且多数元素一定存在。通过排序数组并返回中间位置的元素来找到多数元素。
1220

被折叠的 条评论
为什么被折叠?



