Majority Element_LeetCode
Description:
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.
解题思路:
(方法一):利用vector自带的函数sort()对整个数组进行排序,下标为第n/2的元素必定是出现次数超过 ⌊ n/2 ⌋ 次的数。
代码:
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(),nums.end()); return nums[(nums.size()-1)/2]; } };
-

浙公网安备 33010602011771号