Description:
Given an array of size_n_, find the majority element. The majority element is the element that appearsmore 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: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
思路:题目要求数组中的众数。先将数组中的数字存入 map 结构,key 为元素值,value 为出现的次数,判断 value 次数大于 n/2 则输出 key 值。
C++ 代码
class Solution { public: int majorityElement(vector<int>& nums) { map<int,int> map; for(int num : nums) map[num]++; for(auto it = map.begin(); it !=map.end(); ++it){ if (it->second > nums.size()/2) return it->first; } return 0; } };
运行时间:20ms
运行内存:11.1M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于