跳至主要内容

169. Majority Element

· 閱讀時間約 1 分鐘

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(\log N)$
  • S: $O(1)$