要求求出给定数组中出现频率大于 n / 2的数,那么这个数显然只可能有1个。
题目为:
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.
Example 1:
Input: [3,2,3] Output: 3Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
方法1:
sort后,nums[nums.size() / 2] 一定是所求的众数。
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
方法2:
存入到hash当中,当出现hash[i] > n / 2的情况,该i即为所求,这里没有必要使用。