跳至主要内容

169. Majority Element

Hint - Sort

class Solution {
public:
int majorityElement(vector<int>& nums)
{
// Sort the array in non-decreasing order

// The majority element is guaranteed to be at the middle of the sorted array
// due to the definition of majority element (appears more than n/2 times)
}
};
  • Sort
class Solution {
public:
int majorityElement(vector<int>& nums)
{
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
  • T: O(logN)O(\log N)
  • S: O(1)O(1)