Given an array nums
of size n
, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋
times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3] Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
Constraints:
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109
class Solution {
public:
int majorityElement(vector<int>& nums) {
int MaxKey = 0;
int MaxValue = 0;
unordered_map<int, int>Template;
for (auto x : nums)
{
Template[x]++;
}
for (auto y : Template) {
if (y.second > MaxValue) {
MaxKey = y.first;
MaxValue = y.second;
}
}
return MaxKey;
}
};
這一題我稱為無腦題, 其實Leetcode還蠻多這種無腦題的, 顧名思義就是看到題目就能回答出來的東西, 而這個思路也很簡單, 就是登記一下所有元素出現的次數, 然後把出現次數最高的Key給return 回去, 就是答案了.............. ; 話說我真的掰不出來更多的解釋了.... 哈哈哈 真的很簡單.
留言列表