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.
方法1:直接对数组进行排序,然后中间的那个元素即是。
class Solution {
public:
int majorityElement(vector<int> &num) {
sort(num.begin(),num.end());
return num[(num.size()-1)/2];
}
};
方法2:感觉位运算能解决问题,具体方法暂时不知道。